如何在 java 流中应用双重过滤器?
How to apply double filter in java streams?
我有一个员工 class 有薪水和部门以及员工列表。
static class Employee {
private String department;
private int salary;
//getters
getDeparment()
getSalary()
}
List<Employee>
我需要找出至少有 30 名员工支付了至少 100 美元工资的部门数量。
到目前为止,我已经得到了每个部门的员工数量。但我不确定如何应用过滤器。
HashMap<String, Long> collect = employees
.stream()
.collect(Collectors.groupingBy(Employee::getDepartment, HashMap::new, Collectors.counting()));
如有任何帮助,我们将不胜感激。
HashMap<String, Long> collect = employees
.stream()
.filter(e-> e.getSalary() >= 100 && e.getDeparment().getEmployees().size >= 30)
我不了解你的吸气剂,但你明白了。最后直接收集到map
以下应该可以解决问题:
Set<String> departments = employees.stream()
.filter(employee -> employee.getSalary() >= 100)
.collect(Collectors.groupingBy(Employee::getDepartment, HashMap::new, Collectors.counting()))
.entrySet().stream().filter(entry -> entry.getValue() >= 30)
.map(Map.Entry::getKey)
.collect(Collectors.toSet());
您首先过滤掉 salary
小于 100 的员工。然后按 department
对员工进行分组,并计算 employees
中 employees
的人数12=]。最后,需要过滤掉所有员工少于30人的部门,将最终结果映射到一个Set
.
我有一个员工 class 有薪水和部门以及员工列表。
static class Employee {
private String department;
private int salary;
//getters
getDeparment()
getSalary()
}
List<Employee>
我需要找出至少有 30 名员工支付了至少 100 美元工资的部门数量。
到目前为止,我已经得到了每个部门的员工数量。但我不确定如何应用过滤器。
HashMap<String, Long> collect = employees
.stream()
.collect(Collectors.groupingBy(Employee::getDepartment, HashMap::new, Collectors.counting()));
如有任何帮助,我们将不胜感激。
HashMap<String, Long> collect = employees
.stream()
.filter(e-> e.getSalary() >= 100 && e.getDeparment().getEmployees().size >= 30)
我不了解你的吸气剂,但你明白了。最后直接收集到map
以下应该可以解决问题:
Set<String> departments = employees.stream()
.filter(employee -> employee.getSalary() >= 100)
.collect(Collectors.groupingBy(Employee::getDepartment, HashMap::new, Collectors.counting()))
.entrySet().stream().filter(entry -> entry.getValue() >= 30)
.map(Map.Entry::getKey)
.collect(Collectors.toSet());
您首先过滤掉 salary
小于 100 的员工。然后按 department
对员工进行分组,并计算 employees
中 employees
的人数12=]。最后,需要过滤掉所有员工少于30人的部门,将最终结果映射到一个Set
.