Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

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

ParameterTypeDescription
downstream1Collector<? super T, ?, R1>The first collector.
downstream2Collector<? super T, ?, R2>The second collector.
mergerBiFunction<? 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.0

Notes

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

In the tutorial

  • Collectors — The collect method and the Collectors class — toList, toSet, toMap, joining, counting, summingInt, averagingDouble and the duplicate key error.

Thanks for reading!

Donate to the site — we work hard for you.