Java 12 brought some useful additions and a newly added method ‘Collectors.teeing()’ is one of them. In this post, we will learn “What is teeing() method and how to use it?”.
Here, we are going to learn the following things:
- What is Collectors.teeing() method?
- How to use it?
Collectors.teeing() method in Java 12...!!! Click To Tweet
Let’s Begin,
1. What is Collectors.teeing() method?
It is a static method introduced in Java 12, added into java.util.stream.Collectors interface which allows us to collect using two independent downstream collectors then merges their results using the specified BiFunction.
2. How to use it?
Let’s take an example where we have a list of ‘Agents’ and we are trying to find the highest and lowest ranking agents using ‘Teeing()’ method.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | import java.util.Arrays; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.stream.Collectors; public class Teeing_Collector_Java12_Example { public static void main(String[] args) { List <Agent> agents = Arrays.asList( new Agent("Yash", 9, 8), new Agent("Sam", 5, 13), new Agent("Yashika", 17, 21), new Agent("Diana", 13, 2)); HashMap <String, Agent> agentsRanks = agents.stream().collect( Collectors.teeing( Collectors.maxBy(Comparator.comparing(Agent::getRank)), Collectors.minBy(Comparator.comparing(Agent::getRank)), (e1, e2) -> { HashMap <String, Agent> map = new HashMap <String, Agent> (); map.put("Highest Rank Agent", e1.get()); map.put("Lowest Rank Agent", e2.get()); return map; } )); System.out.println("Highest and Lowest rank values of Agents:\n" + agentsRanks); } } |
Agent (Pojo class):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | public class Agent { String name; int age; int rank; public Agent(String name, int age, int rank) { this.name = name; this.age = age; this.rank = rank; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public int getRank() { return rank; } public void setRank(int rank) { this.rank = rank; } public String toString() { return "Agent [name=" + name + ", age=" + age + ", rank=" + rank + "]"; } } |
Output:
1 2 | Highest and Lowest rank values of Agents: {Lowest Rank Agent=Agent [name=Diana, age=13, rank=2], Highest Rank Agent=Agent [name=Yashika, age=17, rank=21]} |
Collectors.teeing() method in Java 12...!!! Click To Tweet
Do you like this Post? – then check my other helpful posts: