Collectors.teeing()
Sends each element to two collectors at once and combines their results.
Available since: Java 12
Syntax
static <T, R1, R2, R> Collector<T, ?, R> teeing(Collector<? super T, ?, R1> downstream1, Collector<? super T, ?, R2> downstream2, BiFunction<? super R1, ? super R2, R> merger)Parameters
| Parameter | Type | Description |
|---|---|---|
| downstream1 | Collector<? super T, ?, R1> | The first collector. |
| downstream2 | Collector<? super T, ?, R2> | The second collector. |
| merger | BiFunction<? super R1, ? super R2, R> | A function that receives both results and returns the final one. |
Return value
Collector<T, ?, R>A collector whose result is the merger's result.
Examples
Minimum and maximum in a single pass:
record Range(int min, int max) {}
void main() {
Range r = Stream.of(7, 3, 9, 4)
.collect(Collectors.teeing(
Collectors.minBy(Integer::compare),
Collectors.maxBy(Integer::compare),
(min, max) -> new Range(min.get(), max.get())));
IO.println(r);
}Output:
Range[min=3, max=9]An average as the sum divided by the count:
void main() {
double avg = Stream.of(4, 8, 6)
.collect(Collectors.teeing(
Collectors.summingInt(n -> n),
Collectors.counting(),
(sum, count) -> (double) sum / count));
IO.println(avg);
}Output:
6.0Notes
The name comes from a pipe tee: the stream splits into two branches. Useful when a stream cannot be traversed twice or the data is large. For plain numbers summaryStatistics() on an IntStream gives the same.
See also
- Stream.collect() — Gathers stream elements into a collection, a string or another structure.
- Collectors.counting() — A counting collector, usually used inside `groupingBy()`.
- Collectors.summingInt() — A collector that sums a numeric field of the elements.
- BiFunction — A function of two arguments.
In the tutorial
- Collectors — The collect method and the Collectors class — toList, toSet, toMap, joining, counting, summingInt, averagingDouble and the duplicate key error.