Performance Benefits of teeing Over Multiple Passes
You'll learn why using teeing to compute multiple results in a single stream traversal is more efficient than collecting and processing the same stream multiple times.
The Core Efficiency Problem
When you need multiple aggregations from the same data, you might be tempted to collect the stream into a List and then process it twice:
List<Integer> numbers = Stream.of(1, 2, 3, 4, 5)
.collect(Collectors.toList());
int min = numbers.stream().min(Integer::compareTo).orElse(0);
int max = numbers.stream().max(Integer::compareTo).orElse(0);
This approach has three performance costs:
- Memory allocation: You create an intermediate
Listholding all elements - First traversal: Iterating through the stream to build the list
- Additional traversals: Each subsequent
.stream()call iterates again
How teeing Eliminates Waste
Collectors.teeing processes the stream once, applying both collectors simultaneously as each element flows through:
var result = Stream.of(1, 2, 3, 4, 5)
.collect(Collectors.teeing(
Collectors.minBy(Integer::compareTo),
Collectors.maxBy(Integer::compareTo),
(min, max) -> "Min: " + min.get() + ", Max: " + max.get()
));
Think of it like a factory assembly line: instead of running products down the line twice for two different inspections, you station two inspectors side-by-side who examine each product as it passes once.
The Real-World Impact
- No intermediate storage: Elements pass through without being collected first
- Single iteration: The stream pipeline executes only once
- Better for large datasets: Especially important when processing millions of records or expensive computations
Key Takeaway: teeing avoids the memory overhead and redundant iterations of multiple-pass approaches, making it the preferred choice when you need multiple aggregations from the same stream.