Java 12

Java 12 – Teeing Collectors


Java 12 introduces a new method to Collectors to perform two different operations on collection and then merge the result. Following is the syntax of teeing method −

Collector<T, ?, R> teeing(
   Collector<? super T, ?, R1> downstream1,
   Collector<? super T, ?, R2> downstream2, 
   BiFunction<? super R1, ? super R2, R> merger
)

Here we are performing different functions on a collection and then merge the result using merger BiFunction.

Consider the following program −

Java12Teeing.java

import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Java12Teeing {

	public static void main(String[] args) {
		  // Teeing funcation aggregates the results of two supplied collectors
	      double mean
	         = Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9)
	            .collect(Collectors.teeing(
	               Collectors.summingDouble(i -> i), Collectors.counting(),
	               (sum, n) -> sum / n));

	      System.out.println("Aggregate value = " + mean);
	}
}

Output:

Now run the Java8DateTime as follows −

C:\hitechpoints\workspace\java12-feature\src>java Java12Teeing.java

It should produce the following output −

Aggregate value = 5.0

About the Author: Elavarasan PK

Technical Specialist, Intersoft Data Labs