When to Write Custom Collectors vs Compose Existing Ones
You'll learn: How to decide whether building a custom collector from scratch is worthwhile or if combining existing collectors is the better approach.
The Decision Framework
Think of collectors like LEGO blocks versus custom-molded pieces. Standard collectors (groupingBy, mapping, collectingAndThen, teeing) can be combined to solve most problems—just like building with existing LEGO bricks. Custom collectors (Collector.of) are like molding your own special piece: more effort, but sometimes necessary.
When to Compose Existing Collectors
Prefer composition when:
- The logic can be expressed by chaining downstream collectors
- Performance of combined collectors meets your needs
- Code readability isn't significantly harmed
- You're performing common operations (grouping, mapping, filtering, aggregation)
Example: Grouping and transforming can use groupingBy with mapping as downstream—no custom collector needed.
When to Write Custom Collectors
Write custom collectors when:
- No combination exists for your specific accumulation logic
- Performance matters and composition creates unnecessary intermediate objects
- Readability suffers from deeply nested collector chains
- Reusability across your codebase justifies the upfront cost
- Custom data structures require specialized accumulation (like your immutable collection from the previous lesson)
The Cost-Benefit Analysis
Custom collectors require implementing five components (supplier, accumulator, combiner, finisher, characteristics). This is non-trivial effort. If groupingBy(classifier, mapping(mapper, toList())) solves your problem in two lines, don't write 20 lines of custom collector code.
However, if you find yourself repeating complex collector compositions or hitting performance bottlenecks, that's your signal to invest in a custom collector.
Key Takeaway: Default to composing existing collectors for clarity and maintainability; write custom collectors only when composition is impossible, significantly less readable, or demonstrably slower for your use case.