相关疑难解决方法(0)

如何在java流中对groupBy应用过滤

如何先分组,然后使用Java流应用过滤?

示例:考虑此类Employee:我希望按部门分组,其中包含薪水大于2000的员工列表.

public class Employee {
    private String department;
    private Integer salary;
    private String name;

    //getter and setter

    public Employee(String department, Integer salary, String name) {
        this.department = department;
        this.salary = salary;
        this.name = name;
    }
}   
Run Code Online (Sandbox Code Playgroud)

这就是我如何做到这一点

List<Employee> list   = new ArrayList<>();
list.add(new Employee("A", 5000, "A1"));
list.add(new Employee("B", 1000, "B1"));
list.add(new Employee("C", 6000, "C1"));
list.add(new Employee("C", 7000, "C2"));

Map<String, List<Employee>> collect = list.stream()
    .filter(e -> e.getSalary() > 2000)
    .collect(Collectors.groupingBy(Employee::getDepartment));  
Run Code Online (Sandbox Code Playgroud)

产量

{A=[Employee [department=A, salary=5000, name=A1]],
 C=[Employee [department=C, …
Run Code Online (Sandbox Code Playgroud)

java java-8 java-stream collectors java-9

22
推荐指数
3
解决办法
7307
查看次数

标签 统计

collectors ×1

java ×1

java-8 ×1

java-9 ×1

java-stream ×1