Collectors
is a utility class that provides various implementations of reduction operations such as grouping elements, collecting elements to different collections, summarizing elements according to various criteria, etc. The different functionalities in the Collectors
class are usually used as the final operations on streams.
teeing()
is a static method of the Collectors
class that is used to return a Collector
combining the results of two Collector
operations. This method was introduced in Java version 12.
The teeing
method is defined in the Collectors
class. The Collectors
class is defined in the java.util.stream
package. To import the Collectors
class, use the following import statement:
import java.util.stream.Collectors;
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)
Collector<? super T, ?, R1> downstream1
: The first collector.Collector<? super T, ?, R2> downstream2
: The second collector.BiFunction<? super R1,? super R2, R> merger
: The merging function to combine the results of the first and the second collector.This method returns a collector that aggregates the results of two supplied collectors.
import java.util.*;import java.util.stream.Collectors;import java.util.stream.Stream;public class main {static class Person{String name;int age;public Person(String name, int age) {this.name = name;this.age = age;}@Overridepublic String toString() {return "Person{" +"name='" + name + '\'' +", age=" + age +'}';}}public static void main(String[] args) {List<Person> personList = Arrays.asList(new Person("bob", 34), new Person("bob", 43),new Person("mary", 81), new Person("john", 12), new Person("bob", 22));System.out.println("list of person objects - " + personList);Stream<Person> personStream = personList.stream();Map<String, List<Person>> result = personStream.collect(Collectors.teeing(Collectors.filtering(p -> p.age % 2 == 0 , Collectors.toList()),Collectors.filtering(p -> p.age % 2 != 0 , Collectors.toList()),(res1, res2) -> {Map<String, List<Person>> map = new HashMap<>();map.put("EvenAgedPersons", res1);map.put("OddAgedPersons", res2);return map;}));System.out.println("Result of applying teeing - " + result);}}
Person
class with name
and age
as the attributes of the class.Person
objects with different names and age values called personList
.personList
.personList
.teeing
collector on the person stream.filtering
collector that allows only even-aged persons.filtering
collector that allows only odd-aged persons.BiFunction
that takes the results from the two collectors and creates a hashmap of the results.