2

考虑到员工 ID 会增加,目的是找到部门中最新员工的薪水。我已经编写了一个两步代码,我正在尝试找到一个可以使用 java8 一步完成的解决方案。

我的流程是:

  1. 根据该部门中最大的 EmployeeId 获取“部门”的地图:“最新员工”
  2. 使用 Previous Map 创建“Department”:“Salary of the Newest Employee”(这是输出)

是否有可能一步完成?

    public static void main(String[] args) {
    List<Employee> employees = new ArrayList<>();
    Employee e1 = new Employee(1, 1000, "a1", "A");
    Employee e2 = new Employee(2, 1010, "b1", "A");
    Employee e3 = new Employee(3, 1000, "a1", "B");
    Employee e4 = new Employee(4, 500, "b2", "B");
    Employee e5 = new Employee(5, 2000, "a1", "C");
    Employee e6 = new Employee(6, 5000, "b2", "C");
    employees.add(e1);
    employees.add(e2);
    employees.add(e3);
    employees.add(e4);
    employees.add(e5);
    employees.add(e6);
    //This Map will contain Department and The newest Employee in that Department.
    Map<String, Employee> retVal = employees.stream()
            .collect(groupingBy(
                    e -> e.getDepartment(),
                    collectingAndThen(maxBy(comparingInt(e -> e.getEmployeeId())), Optional::get)
            ));
    //This Map will use the previous map to construct a combination of "Department" : "Salary of the newest Member"
    Map<String, Integer> map = new HashMap<>();
    retVal.entrySet().forEach(stringEmployeeEntry -> {
        map.put(stringEmployeeEntry.getKey(), stringEmployeeEntry.getValue().getSalary());
    });
}

输出

{
  "a1" : 2000,
  "b1" : 1010,
  "b2" : 5000, 
}
4

1 回答 1

2

collectingAndThen您可以直接从Employee对象映射薪水

Map<String, Integer> retVal = employees.stream()
            .collect(Collectors.groupingBy(
                    e -> e.getDepartment(),
                    Collectors.collectingAndThen(
                         Collectors.maxBy(Comparator.comparingInt(e -> e.getEmployeeId())),
                         e -> e.get().getSalary())
            ));
于 2020-10-04T12:20:32.787 回答