【问题标题】:How to apply double filter in java streams?java - 如何在java流中应用双重过滤器?
【发布时间】:2021-11-18 22:18:37
【问题描述】:

我有一个 Employee 类,其中包含薪水和部门以及员工列表。

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()));

任何帮助将不胜感激。

【问题讨论】:

  • 我想下一步是做一个类似的语句来收集每个部门的最低工资。然后尝试将两者结合在一起。
  • 至于应用过滤器,您应该可以将.stream().filter() 添加到您目前所拥有的内容中。

标签: java java-stream


【解决方案1】:

以下应该可以解决问题:

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 对员工进行分组,并计算 departmentemployees 的数量。最后,您需要过滤掉所有员工人数少于 30 人的部门,并将最终结果映射到 Set

【讨论】:

  • 通过链接更多方法,这看起来是正确的方向。但是,我认为这不会使“部门的最低工资为100”。我将其解读为“在每个部门的所有员工中获得最低工资。然后选择任何一个至少有 100 的部门。”
【解决方案2】:
  HashMap<String, Long> collect = employees
                .stream()
                .filter(e-> e.getSalary() >= 100 && e.getDeparment().getEmployees().size >= 30)

我不知道你的吸气剂,但你明白了。最后只是把它收集到地图上

【讨论】:

  • 更新了我的吸气剂。我没有必须从员工列表中派生的部门中的员工
  • 你的部门班级看起来怎么样?
  • 看起来部门是一个字符串,没有类。
  • 哦,那就用@João Dias 回答我还以为你那里也有对象
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-08
相关资源
最近更新 更多