java员工编号程序,使用Java流根据薪水检索员工部门和ID

I have a list of Employees

[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]

I want to collect department and id of the employee with maximum salary in that department in a Map.

Sample Output:

Engineering 22

Testing 23

The attempted code

Map> retVal = new HashMap>();

retVal = employeeList.stream().collect(Collectors.groupingBy(Employee::getDepartment,Collectors.maxBy(Comparator.comparing(Employee::getSalary))));

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 - 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> 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 - 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.

#3 - lookup approach

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 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 retVal = employeeList.stream()

.collect(Collectors.toMap(Employee::getDepartment, Employee::getId,

BinaryOperator.maxBy(Comparator.comparing(employeeSalary::get))));

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值