еңЁJava12дёӯпјҢCollectors APIе·Із»Ҹжү©еұ•дәҶдёҖдёӘйқҷжҖҒзҡ„teeting(...)еҮҪж•°пјҡ
teetingвҖӢ(Collector<? super T,вҖӢ?,вҖӢR1> downstream1,
Collector<? super T,вҖӢ?,вҖӢR2> downstream2,
BiFunction<? super R1,вҖӢ? super R2,вҖӢR> merger)
иҝҷжҸҗдҫӣдәҶдёҖдёӘеҶ…зҪ®еҠҹиғҪпјҢеҸҜд»ҘеңЁдёҖдёӘStreamдёҠдҪҝз”ЁдёӨдёӘ收йӣҶеҷЁпјҢ并е°Ҷз»“жһңеҗҲ并дёәдёҖдёӘеҜ№иұЎгҖӮ
д»ҘдёӢжҳҜдёҖдёӘе°ҸдҫӢеӯҗпјҢе…¶дёӯе°Ҷе‘ҳе·ҘеҲ—иЎЁеҲҶжҲҗе№ҙйҫ„з»„пјҢ并еҜ№жҜҸдёӘз»„жү§иЎҢдёӨдёӘCollectors.summarizingInt()пјҲеҜ№е№ҙйҫ„е’Ңи–Әж°ҙпјүиҝ”еӣһдҪңдёәIntSummaryStatisticsеҲ—иЎЁпјҡ
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
public class CollectorTeeingTest {
public static void main(String... args){
NavigableSet<Integer> age_groups = new TreeSet<>();
age_groups.addAll(List.of(30,40,50,60,Integer.MAX_VALUE));
Function<Integer,Integer> to_age_groups = age -> age_groups.higher(age);
List<Employee> employees = List.of( new Employee("A",21,2000),
new Employee("B",24,2400),
new Employee("C",32,3000),
new Employee("D",40,4000),
new Employee("E",41,4100),
new Employee("F",61,6100)
);
Map<Integer,List<IntSummaryStatistics>> stats = employees.stream()
.collect(Collectors.groupingBy(
employee -> to_age_groups.apply(employee.getAge()),
Collectors.teeing(
Collectors.summarizingInt(Employee::getAge),
Collectors.summarizingInt(Employee::getSalary),
(stat1, stat2) -> List.of(stat1,stat2))));
stats.entrySet().stream().forEach(entry -> {
System.out.println("Age-group: <"+entry.getKey()+"\n"+entry.getValue());
});
}
public static class Employee{
private final String name;
private final int age;
private final int salary;
public Employee(String name, int age, int salary){
this.name = name;
this.age = age;
this.salary = salary;
}
public String getName(){return this.name;}
public int getAge(){return this.age;}
public int getSalary(){return this.salary;}
}
}
输出:
Age-group: <2147483647
[IntSummaryStatistics{count=1, sum=61, min=61, average=61,000000, max=61}, IntSummaryStatistics{count=1, sum=6100, min=6100, average=6100,000000, max=6100}]
Age-group: <50
[IntSummaryStatistics{count=2, sum=81, min=40, average=40,500000, max=41}, IntSummaryStatistics{count=2, sum=8100, min=4000, average=4050,000000, max=4100}]
Age-group: <40
[IntSummaryStatistics{count=1, sum=32, min=32, average=32,000000, max=32}, IntSummaryStatistics{count=1, sum=3000, min=3000, average=3000,000000, max=3000}]
Age-group: <30
[IntSummaryStatistics{count=2, sum=45, min=21, average=22,500000, max=24}, IntSummaryStatistics{count=2, sum=4400, min=2000, average=2200,000000, max=2400}]