144 Java - Teeing Collectors
Java Collectors.teeing() Method
Java 12 introduced a new static method to Collectors interface which can perform two different operations on collection and then merge the result.
Syntax
Following is the syntax of teeing method −
public static Collector<T, ?, R> teeing( Collector<? super T, ?, R1> downstream1, Collector<? super T, ?, R2> downstream2, BiFunction<? super R1, ? super R2, R> merger )
Here each element of the collection passed to the teeing collector is processed by downstream1 and downstream2 collectors, once the processing is completed by both the collectors, the results are passed to the BiFunction collector to merge the result or process accordingly. It is similar to calling two functions on a collection and then calling the third function to process the results of first two functions.
Here we are performing different functions on a collection and then merge the result using merger BiFunction.
Example - Using teeing collectors to get mean of n numbers
In this example, we're getting sum of numbers in downstream1 collector, count of numbers in downstream2 collector and then computing mean in the merger function. This is useful when we're getting a stream of numbers and size of stream is not available.
Output
Let us compile and run the above program, this will produce the following result −
4.0
Example - Using teeing collectors to get lowest and highest marks of student objects
In this example, we're getting lowest marks of students in downstream1 collector and highest marks of students in downstream2 collector. Then using merger function, we're creating a hashmap with entry of student having lowest and highest marks.
Output
Let us compile and run the above program, this will produce the following result −
{Lowest=Student [RollNo=1, Name=Robert, Marks=390], Highest=Student [RollNo=3, Name=John, Marks=440]}

Comments
Post a Comment