Collectors.teeing()
Compute two aggregations in a single stream pass.
Code Comparison
✕ Java 8
long count = items.stream().count();
double sum = items.stream()
.mapToDouble(Item::price)
.sum();
var result = new Stats(count, sum);
✓ Java 12+
var result = items.stream().collect(
Collectors.teeing(
Collectors.counting(),
Collectors.summingDouble(Item::price),
Stats::new
)
);
Why the modern way wins
Single pass
Process the stream once instead of twice.
Composable
Combine any two collectors with a merger function.
Immutable result
Merge into a record or value object directly.
Old Approach
Two Passes
Modern Approach
teeing()
Since JDK
12
Difficulty
intermediate
JDK Support
Collectors.teeing()
Available
Widely available since JDK 12 (March 2019)
How it works
Collectors.teeing() sends each element to two downstream collectors and merges the results. This avoids streaming the data twice or using a mutable accumulator.