groupby java_如何在Java流中对groupBy应用过滤

论坛 期权论坛 编程之家     
选择匿名的用户   2021-6-2 20:50   1484   0

您如何先分组然后使用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;

}

}

这就是我可以做到的

List 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> collect = list.stream()

.filter(e -> e.getSalary() > 2000)

.collect(Collectors.groupingBy(Employee::getDepartment));

输出量

{A=[Employee [department=A, salary=5000, name=A1]],

C=[Employee [department=C, salary=6000, name=C1], Employee [department=C, salary=7000, name=C2]]}

由于B部门中没有雇员的薪水高于2000。因此B部门没有密钥: 但是实际上,我想使用空列表作为密钥–

预期产量

{A=[Employee [department=A, salary=5000, name=A1]],

B=[],

C=[Employee [department=C, salary=6000, name=C1], Employee [department=C, salary=7000, name=C2]]}

我们应该怎么做?

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:3875789
帖子:775174
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP