Combining Count and Sum with teeing
You'll learn how to calculate both count and sum simultaneously with teeing, then merge them into a single result like an average.
The Core Idea
Sometimes you need multiple pieces of information from a stream—like the total count and total sum—to perform a calculation such as finding an average. Without teeing, you'd process the stream twice or resort to complex workarounds. The teeing collector lets you run two downstream collectors in parallel on the same stream, then merge their results with a custom function.
Think of it like a restaurant splitting one order between two cooks who each prepare part of the dish, then a third person combines their work into the final plate.
Calculating Average with teeing
Here's how to compute an average by simultaneously counting elements and summing values:
import java.util.stream.Collectors;
import java.util.List;
List<Integer> numbers = List.of(10, 20, 30, 40, 50);
Double average = numbers.stream()
.collect(Collectors.teeing(
Collectors.counting(), // First downstream: count
Collectors.summingInt(n -> n), // Second downstream: sum
(count, sum) -> sum / (double) count // Merge function
));
System.out.println(average); // Output: 30.0
The teeing collector processes each element through both counting() and summingInt(), then passes the results to your merge function (count, sum) -> sum / (double) count, which calculates the average.
Why This Matters
Without teeing, you'd need two separate stream operations or collect to an intermediate data structure—both less efficient and less elegant.
Key Takeaway:
teeing with counting() and summingInt() calculates both count and sum in a single stream pass, letting you merge them (like computing an average) without reprocessing data.