Member-only story

Java Stream API: Exploring Collectors.teeing() collector

Eric Anicet

--

The Collector.teeing feature introduced in Java 12 is a powerful addition to the Collector interface in the Java Stream API.

The teeing() method

teeing() is a static method of the Collectors class that is used to return a Collector combining the results of two Collector operations. Every element passed to the resulting collector is processed by both downstream collectors, then their results are merged using the specified merge function into the final result.

Syntax

public 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
)

Explanation

The Collector.teeing method takes three arguments:

  • Collector<? super T, ?, R1> downstream1: The first downstream collector that collects elements from the stream.
  • Collector<? super T, ?, R2> downstream2: The second downstream collector also collects elements from the stream.
  • BiFunction<? super R1,? super R2, R> merger: The merging function to combine the results of the first and the second collector.

--

--

No responses yet

Write a response