Teeing collector take two different collectors to transform the elements of a Stream and then merge the result.
Signature
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)
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
Parameters:
downstream1 - the first downstream collector
downstream2 - the second downstream collector
merger - the function which merges two results into the single one
Returns:
a Collector which aggregates the results of two supplied collectors.
Example
Following snippet finds minimum and maximum age of employees in a stream.
employeeAges.stream().collect(teeing(minBy(Integer::compareTo), maxBy(Integer::compareTo), (minAge, maxAge) -> {
return new EmployeeMinMaxAge(minAge.get(), maxAge.get());
}));
Find the below working example.
EmployeeMinMaxAge.java
package com.sample.app.model;
public class EmployeeMinMaxAge {
private int minAge;
private int maxAge;
public EmployeeMinMaxAge(int minAge, int maxAge) {
super();
this.minAge = minAge;
this.maxAge = maxAge;
}
public int getMinAge() {
return minAge;
}
public void setMinAge(int minAge) {
this.minAge = minAge;
}
public int getMaxAge() {
return maxAge;
}
public void setMaxAge(int maxAge) {
this.maxAge = maxAge;
}
@Override
public String toString() {
return "EmployeeMinMaxAge [minAge=" + minAge + ", maxAge=" + maxAge + "]";
}
}
TeeingExample.java
package com.sample.app.streams;
import static java.util.stream.Collectors.maxBy;
import static java.util.stream.Collectors.minBy;
import static java.util.stream.Collectors.teeing;
import java.util.Arrays;
import java.util.List;
import com.sample.app.model.EmployeeMinMaxAge;
public class TeeingExample {
public static void main(String args[]) {
List<Integer> employeeAges = Arrays.asList(19, 23, 44, 35, 36, 65, 50, 43);
EmployeeMinMaxAge empMinAndMaxAge = employeeAges.stream()
.collect(teeing(minBy(Integer::compareTo), maxBy(Integer::compareTo), (minAge, maxAge) -> {
return new EmployeeMinMaxAge(minAge.get(), maxAge.get());
}));
System.out.println(empMinAndMaxAge);
}
}
Output
EmployeeMinMaxAge [minAge=19, maxAge=65]
You can download java12 examples from below link.
https://github.com/harikrishna553/java12-demo
Reference
https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/util/stream/Collectors.html#teeing(java.util.stream.Collector,java.util.stream.Collector,java.util.function.BiFunction)Previous Next Home
No comments:
Post a Comment