teeing-collector-java12
Java

Java 12: Teeing Collector

Java12-Teeing Collector

Collector While writing Java programs, sometimes it becomes necessary to collect the stream elements or any other data using two collectors. Otherwise, it may lead to error prone cases in coding level. There is no such solution to such problems in our existing JDK of Java. Here Java 12 JDK comes with a proper solution for such problems by adding a new Stream API Collector to JDK 12 (i.e, Teeing Collector), which has an initial release within two weeks of time.

Java 12 (JDK 12) adds a new static method teeing to our existing java.util.stream. Collectors interface. The purpose of teeing collector is to collect streams and return collector using two independent collectors, then merge their results using the specified function by java 12, called BiFunction.

The Proposed idea by Java 12 adds more flexibility in programming level, the user can use their own Pair class like teeing (first_collector, second_collector, Pair:: new) or can combine the results in some other way according to users’ needs. The final part of teeing collector can be changed according to our desire. If a particular user needs the results to be returned in Map. Entry format, then the teeing collector must be specify the result as teeing (first_collector, second_collector, Map:: entry).

The method signature for the Collector:: Teeing is, Collector) >. In this first section of collector tags specify the elements to be collected using the collector, second parameter holds the type of the elements being collected and at the same time third parameter specifies the type of result the user needs.

After introducing teeing collector, the solution to a particular problem can be done as
// import static java.util.stream.Collectors.*;

Double average = Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) .collect(teeing( summingDouble(i ->
i),counting(), (sum, count) -> sum / count));

System.out.println(average); // 3.5

If the user needs the exact functionality of an existing collector for one or even both of them, he/she cannot apply the previously implemented solution and must have to rewrite that again. Now, from the release of Java 12 on-wards that’s no longer the case

Link to go through: http://cr.openjdk.java.net/~tvaleev/webrev/8205461/r6/

Author: STEPS

Leave a Reply

Your email address will not be published. Required fields are marked *