Pages

Tuesday, April 30, 2019

Java 12 Collectors.teeing() - Working Examples

1. Overview

In this post, We will learn about new method teeing () added in Java 12 to Collectors class. Collectors class is in package java.util.stream.Collector and it is in java.base module.


Java 12 Collector.teeing​() Method with Example


2. Collectors.teeing ()

Returns a Collector that is a composite of two downstream collectors. 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. 



The resulting collector functions do the following:


    supplier: creates a result container that contains result containers obtained by calling each collector's supplier

    accumulator: calls each collector's accumulator with its result container and the input element
    combiner: calls each collector's combiner with two result containers
    finisher: calls each collector's finisher with its result container, then calls the supplied merger and returns its result. 

Note: 
The resulting collector is Collector.Characteristics.UNORDERED if both downstream collectors are unordered and Collector.Characteristics.CONCURRENT if both downstream collectors are concurrent.

2.1 Syntax:



public static  Collector teeing​(Collector downstream1, Collector downstream2, BiFunction merger)


2.2 Type Parameters

    T - the type of the input elements
    R1 - the result type of the first collector
    R2 - the result type of the second collector
    R - the final result type

2.3 Parameters


    downstream1 - the first downstream collector

    downstream2 - the second downstream collector
    merger - the function which merges two results into the single one

2.4 Returns

    a Collector which aggregates the results of two supplied collectors.


3. Example 1


Here taking two collectors named as joiningCollector and listCollector.


joiningCollector - Joins all given strings with delimiter '-'

listCollector - Adds the all given strings to List.

teeingCollector --> This takes two inputs from above two collectors output.




package examples.java.w3schools.java12.collectors;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collector;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class CollectorsTeeingExample {

 public static void main(String[] args) {
  // Returns a Collector that concatenates the input elements,separated by the
  // specified delimiter, in encounter order.
  Collector joiningCollector = Collectors.joining("-");

  // Returns a Collector that accumulates the input elements into anew List.
  Collector> listCollector = Collectors.toList();

  Collector teeingCollector = Collectors.teeing(joiningCollector, listCollector,
    (joinedString, stringsList) -> {
     ArrayList list = new ArrayList<>(stringsList);
     list.add(joinedString);
     String[] array = list.toArray(new String[0]);
     return array;
    });
  String[] words = Stream.of("Java", "W3schools", "blog").collect(teeingCollector);
  System.out.println("Output of Collector teeing method in String[] Array : " + Arrays.toString(words));
 }

}

Output:

This program compiles and runs successfully in JDK 12 or above Java 12 version.


Output of Collector teeing method in String[] Array : [Java, W3schools, blog, Java-W3schools-blog]


In the above program, 
joinedString is a String that joins all the strings in word array. The value in the String variable joinedString is "Java-W3schools-blog"
stringsList is a list that is created with the words string array. The values are the stringsList : [Java, W3schools, blog]

Now see the code inside teeingCollector, first two input paramters are output of joiningCollector, listCollector. The output of these two collectors are passed as input to the teeingCollector. After that, creating new ArrayList as named list with values stringsList and adding joinedString to the list. 


Finally, Converting list into String[] array because teeingCollector expecting String[] as output.

String[] array = list.toArray(new String[0]);

4. Example 2

Finding Average of first 10 numbers using Collector teeing Method: We will write a program to find the average of first 10 numbers using teeing method and another two collector methods such as summingDouble() and counting() method.

package examples.java.w3schools.java12.collectors;

import static java.util.stream.Collectors.counting;
import static java.util.stream.Collectors.summingDouble;
import static java.util.stream.Collectors.teeing;

import java.util.stream.Stream;

public class TeeingCountExample {

 public static void main(String[] args) {
  // Converting 1 to 10 numbers into Stream integer array.
  Stream stream = Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

  // Calling teeing method.
  Double average = stream.collect(teeing(summingDouble(i -> i), counting(), (sum, n) -> sum / n));

  System.out.println("Average of first 10 numbers: " + average);
 }
}

Here summingDouble(), counting(), teeing() methods are static methods in Collector class and we have used static import for class Collectors.

Output:

Average of first 10 numbers: 5.5

Other Examples on teeing collector using minBy, maxBy 


See the JDK JIRA ticket for Create Collector which merges results of two other collectors.


5. Conclusion


In this tutorial, We have covered new method that added in jdk 12 Collector class. Further discussed a few example programs on this method to merge two collectors output into one.

1 comment:

Please do not add any spam links in the comments section.