【发布时间】:2018-01-16 02:00:42
【问题描述】:
如何先分组,然后使用 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<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));
输出
{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]]}
我们该怎么做?
【问题讨论】:
-
版本标签应用于特定于该版本的问题。如果这是关于跨多个版本的流,它不应该有任何标签 IMO。
标签: java java-8 java-stream java-9 collectors