使用Java流根据薪水检索员工部门和ID [英] Retrieving employee department and id based on the salary using Java streams
问题描述
我有一个员工列表
[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>
中收集该部门中薪水最高的员工的部门和编号.
I want to collect department and id of the employee with maximum salary in that department in a Map<String,Integer>
.
示例输出:
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作为值.
This implementation I have added and I am getting department as a key and the highest salary Employee as a value but I want only employee id as the value.
推荐答案
#1-当前方法
提供了您尝试过的内容,您可以扩展相同的管道以再次在条目上进行流传输并按如下所示映射值:
#1 - current approach
Provided what you've attempted, you can extend the same pipeline to stream again over the entries and map the values as following:
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
操作执行该操作,则可以使用
#2 - single stream approach
Now if you were to look for abstracting the streaming over entries and perform the operation with a single collect
operation, then you can make use of Hadi's solution.
作为一个建议(尽管有两次迭代),如果我要扩展它并使其灵活以便将来使用,我首先要准备一个ID到员工工资的查找映射表
As a suggestion(though with two times iteration), if I was to extend this and make it flexible for further use, I would first prepare a lookup map for the id to the salary of the employees
Map<Integer, Integer> employeeSalary = employeeList.stream()
.collect(Collectors.toMap(Employee::getId, Employee::getSalary));
使用此地图进一步获得当前所需的地图也很方便,例如:
using this map to further attain the mapping as you currently desire is also convenient though, such as :
Map<String, Integer> retVal = employeeList.stream()
.collect(Collectors.toMap(Employee::getDepartment, Employee::getId,
BinaryOperator.maxBy(Comparator.comparing(employeeSalary::get))));
这篇关于使用Java流根据薪水检索员工部门和ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!