Basic teeing Example: Min and Max in One Pass
You'll learn how to use Collectors.teeing() to compute both the minimum and maximum values from a stream in a single pass.
The Problem teeing Solves
Imagine you need to find both the smallest and largest item in a collection. Traditionally, you'd either traverse the collection twice (once for min(), once for max()), or write custom logic. The teeing collector elegantly solves this by applying two collectors simultaneously during a single stream pass.
How It Works
The teeing collector takes three arguments:
- First downstream collector – computes one result (e.g., minimum)
- Second downstream collector – computes another result (e.g., maximum)
- Merger function – combines both results into a final output
Think of it like a highway toll booth with two cameras: one captures your entry time (minimum), another your exit time (maximum), and the system merges them into a single toll record.
Simple Example: Finding Min and Max
List<Integer> numbers = Arrays.asList(5, 2, 9, 1, 7, 3);
var result = numbers.stream()
.collect(Collectors.teeing(
Collectors.minBy(Comparator.naturalOrder()),
Collectors.maxBy(Comparator.naturalOrder()),
(min, max) -> "Min: " + min.orElse(null) + ", Max: " + max.orElse(null)
));
System.out.println(result); // Min: Optional[1], Max: Optional[9]
Here, we're using minBy and maxBy (which return Optional results) as our two collectors. The merger function receives both optionals and formats them into a readable string. The stream is traversed only once, yet we get both extremes.
Key Takeaway:
Collectors.teeing() lets you apply two collectors to the same stream simultaneously, computing multiple aggregations in a single pass—perfect for finding min and max together efficiently.