When to Use teeing vs Separate Collectors
You'll learn: How to decide when teeing provides real value versus when separate collection operations or intermediate steps are clearer and more maintainable.
The Decision Point
Just because teeing can combine two collectors in one pass doesn't mean you should always use it. The key question: Does combining these operations genuinely improve your code, or does it just make it more complex?
When teeing Adds Value
Use teeing when:
- You need exactly two aggregations on the same stream
- The cost of traversing the stream twice is significant (large data, expensive operations)
- The results logically belong together (min/max pair, count/sum for average calculation)
- The code remains readable with the combined collectors
// Good teeing use: naturally paired results
Statistics stats = employees.stream()
.collect(Collectors.teeing(
Collectors.counting(),
Collectors.summingInt(Employee::getSalary),
(count, sum) -> new Statistics(count, sum / count)
));
When Separate Collectors Are Clearer
Avoid teeing when:
- You need more than two aggregations (becomes unreadable)
- The operations are logically unrelated
- Debugging would be easier with separate steps
- The stream is small (performance gain negligible)
// Clearer as separate operations
long count = employees.stream().count();
int totalSalary = employees.stream()
.mapToInt(Employee::getSalary)
.sum();
// Easy to debug, understand, and modify
Think of teeing like a double-bladed tool: powerful for specific paired tasks, but awkward for general use. When your collectors naturally complement each other and performance matters, reach for teeing. Otherwise, favor clarity.
Key Takeaway: Use teeing for paired aggregations on expensive streams where readability isn't sacrificed; prefer separate collectors when clarity, debugging, or multiple aggregations matter more than the single-pass performance benefit.