Java 8 lambda用于为每个部门选择最高薪资员工 [英] Java 8 lambda for selecting top salary employee for each department

查看:98
本文介绍了Java 8 lambda用于为每个部门选择最高薪资员工的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class Employee {
    public string department;
    public int salary;
}

List<Employee> allEmployees = ...

我需要有一个列表,每个列表只有1个最高薪员工部门。 allEmployees是源列表。

I need to have a list that will have only 1 top salary employee for each department. allEmployees is the source list.

推荐答案

你可以用分组收集器来做到这一点:

You can do that with a grouping collector:

Map<String, Employee> topEmployees =
    allEmployees.stream()
                .collect(groupingBy(
                    e -> e.department,
                    collectingAndThen(maxBy(comparingInt(e -> e.salary)), Optional::get) 
                ));

静态导入

import static java.util.Comparator.comparingInt;
import static java.util.stream.Collectors.collectingAndThen;
import static java.util.stream.Collectors.groupingBy;
import static java.util.stream.Collectors.maxBy;

此代码创建所有的员工并在 Collectors.groupingBy 。对于分类到相同密钥的所有值,我们只需要保留具有最大工资的员工,因此我们使用 Collectors.maxBy 并且比较器比较的工资 Comparator.comparingInt 。由于 maxBy 返回可选< Employee> (为了处理列表为空的情况),我们将其换行致电 Collectors.collectingAndThen ,其中有一个刚刚返回员工的终结者:我们知道在这种情况下可选赢了不算空。

This code creates a Stream of all the employees and groups them with their department with the help of Collectors.groupingBy. For all the values classified to the same key, we need to keep only the employee with the maximum salary, so we collect them with Collectors.maxBy and the comparator compares the salary with Comparator.comparingInt. Since maxBy returns an Optional<Employee> (to handle the case where there the list is empty), we wrap it with a call to Collectors.collectingAndThen with a finisher that just returns the employee: we know in this case that the optional won't be empty.

这篇关于Java 8 lambda用于为每个部门选择最高薪资员工的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆