【问题标题】:Retrieving employee department and id based on the salary using Java streams使用 Java 流根据工资检索员工部门和 ID
【发布时间】:2020-07-05 07:49:51
【问题描述】:

我有一份员工名单

[employeeId=22, employeeName= Rajan Anand, department= Engineering, salary=1600000]

[employeeId=23, employeeName= Swati Patil, department= Testing, salary=800000]

[employeeId=27, employeeName= Vijay Chawda, department= Engineering, salary=800000]

[employeeId=29, employeeName= Basant Mahapatra, department= Engineering, salary=600000]

[employeeId=32, employeeName= Ajay Patel, department= Testing, salary=350000]

[employeeId=34, employeeName= Swaraj Birla, department= Testing, salary=350000]

我想在Map<String,Integer> 中收集该部门最高薪员工的部门和 ID。

样本输出

Engineering 22

Testing 23

尝试的代码

Map<String, Optional<Employee>> retVal = new HashMap<String, Optional<Employee>>();
retVal = employeeList.stream().collect(Collectors.groupingBy(Employee::getDepartment,Collectors.maxBy(Comparator.comparing(Employee::getSalary))));

我已经添加了这个实现,我将部门作为键和最高薪水的员工作为值,但我只想要员工 ID 作为值。

【问题讨论】:

    标签: java java-8 collectors


    【解决方案1】:

    #1 - 当前方法

    如果您尝试过,您可以扩展相同的管道以再次流过条目并将值映射如下:

    Map<String, Optional<Integer>> retVal = employeeList.stream()
            .collect(Collectors.groupingBy(Employee::getDepartment,
                    Collectors.maxBy(Comparator.comparing(Employee::getSalary))))
            .entrySet().stream()
            .collect(Collectors.toMap(Map.Entry::getKey,
                    e -> e.getValue().map(Employee::getId)));
    

    #2 - 单流方法

    现在,如果您要寻找对条目进行流式处理并使用单个 collect 操作执行操作,那么您可以使用 Hadi's solution

    #3 - 查找方法

    作为一个建议(虽然有两次迭代),如果我要扩展它并使其灵活以供进一步使用,我会首先准备一个查找映射,用于 id 到员工的薪水

    Map<Integer, Integer> employeeSalary = employeeList.stream()
            .collect(Collectors.toMap(Employee::getId, Employee::getSalary));
    

    使用此地图进一步实现您当前想要的映射也很方便,例如:

    Map<String, Integer> retVal = employeeList.stream()
            .collect(Collectors.toMap(Employee::getDepartment, Employee::getId,
                    BinaryOperator.maxBy(Comparator.comparing(employeeSalary::get))));
    

    【讨论】:

      【解决方案2】:

      你可以这样做:

      Map<String, Optional<Integer>> result =  employeeList.stream()
           .collect(Collectors.groupingBy(Employee::getDepartment,
                    Collectors.collectingAndThen(Collectors
                         .maxBy(Comparator.comparing(Employee::getSalary)),
                                                  e-> e.map(Employee::getEmployeeId))));
      

      DEMO

      【讨论】:

      • 感谢@Haldi 的帮助
      • @NoopurSrivastava,我猜emplyeeId 不为空。如果你想拥有Map&lt;String,Integer&gt;,那么你可以使用e-&gt; e.map(Employee::getEmployeeId).orElse(-1)。 -1 代表 null employeeId
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-01-25
      • 2013-05-23
      • 2021-01-14
      • 1970-01-01
      • 2021-09-09
      • 2014-05-17
      • 1970-01-01
      相关资源
      最近更新 更多