Composite Pattern Implementation in Java
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Composite Pattern runs in O(n) time and O(n) space, in Java as in every other language.
- ✓An interface implemented by a leaf class and a composite class holding a List of the interface.
- ✓Prefer a sealed interface with records for the node types, which gives exhaustive switches, value semantics and a readable toString for free, and which reviewers now expect over an abstract class.
- ✓The Java trap: The default thread stack is around half a megabyte to a megabyte depending on platform, giving roughly ten to twenty thousand frames, and exceeding it throws StackOverflowError, which is an Error rather than an Exception: it is not caught by a catch of Exception, it can leave objects half-initialised, and catching it and continuing is unsafe because the stack may unwind mid-operation.
- ✓Recursive traversal costs a frame per level, which the JIT can sometimes flatten but not across a virtual call it cannot devirtualise, and a composite whose children are typed as the interface is exactly the case it cannot.
What Composite Pattern actually is
Composite Pattern in Java: what you actually reach for
Java implementation
import java.util.*;
import java.util.stream.*;
sealed interface Node permits Leaf, Branch {}
record Leaf(int size) implements Node {}
record Branch(List<Node> children) implements Node {
Branch { children = List.copyOf(children); } // unmodifiable, defensively copied
}
class Trees {
// Java 21 record patterns: destructure in the case label, exhaustive, no default.
static int total(Node n) {
return switch (n) {
case Leaf(int size) -> size;
case Branch(List<Node> kids) -> kids.stream().mapToInt(Trees::total).sum();
};
}
// Explicit stack: no frames, no StackOverflowError on a deep tree.
static int totalIterative(Node root) {
Deque<Node> stack = new ArrayDeque<>(List.of(root));
int acc = 0;
while (!stack.isEmpty()) {
if (stack.pop() instanceof Leaf l) acc += l.size();
else if (stack.peek() == null) continue;
}
return acc;
}
}Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe Java-specific trap
Performance in Java, beyond the O(n)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Java type or library should I use for Composite Pattern?
An interface implemented by a leaf class and a composite class holding a List of the interface. The platform gives you two composites to model on: java.io.File and the newer java.nio.file.Path with Files.walk and Files.walkFileTree, the latter taking a FileVisitor whose return values control pruning. Since Java 17 a sealed interface permitting exactly Leaf and Branch lets the compiler check a switch for exhaustiveness, and Java 21 pattern matching for switch with record patterns destructures the node in the case label.
What is the most common Java mistake when implementing Composite Pattern?
The default thread stack is around half a megabyte to a megabyte depending on platform, giving roughly ten to twenty thousand frames, and exceeding it throws StackOverflowError, which is an Error rather than an Exception: it is not caught by a catch of Exception, it can leave objects half-initialised, and catching it and continuing is unsafe because the stack may unwind mid-operation. Files.walk in particular is depth-first and lazily opens directory streams, so failing to close the returned stream leaks file descriptors until the process runs out.
How does Composite Pattern actually perform in Java?
Recursive traversal costs a frame per level, which the JIT can sometimes flatten but not across a virtual call it cannot devirtualise, and a composite whose children are typed as the interface is exactly the case it cannot. An explicit ArrayDeque used as a stack avoids the frames and is usually faster on large trees. Streams add per-element overhead that is invisible for a thousand nodes and material for ten million; the flatMap-based recursive stream in particular allocates a stream object per branch. Time complexity is O(n) and space is O(n).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialBefore paying for GitHub Copilot, check its student and free-tier options on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.