[Java] Collectors

 

Stream<Employee> emps = ...

TreeSet<Employee> tree = emps.collect(
    Collectors.toCollection(
        () -> new TreeSet<Employee>(
            Comparator.comparingInt(Employee:getSalary)
    )
);

 

Build a map from employees' names t otheir salaries

Stream<Employee> emps = ...

Map<String, Integer> salaries = emps.collect(
    Collectors.toMap(Employee::getName, Employee::getSalary)
);

 

Group employees by Salary brackets

first bracket: 0-999

2nd bracket: 1000-1999

Stream<Employee> emps = ...

Map<Integer, List<Employee>> brackets = 
    emps.collect(Collectors.groupBy(
        e -> e.getSalary()/1000
    )
);

 

posted @ 2021-01-22 20:17  Zhentiw  阅读(137)  评论(0编辑  收藏  举报