首页 > 解决方案 > 如何使用 Java 流在 groupby 之后应用排序和限制

问题描述

我有以下员工数据列表,我需要根据员工部门对其进行分组,然后我想找到每个部门中薪酬最高的 2 名员工。

public class Employee {

    private int id;
    private String name;
    private String dept;
    private int salary;

    //setters and getters
}

List<Employee> listOfEmp = new ArrayList<>();

listOfEmp.add(new Employee (1, "A", "IT",100));
listOfEmp.add(new Employee (2, "B", "IT",200));
listOfEmp.add(new Employee (3, "C", "SUPPORT",100));
listOfEmp.add(new Employee (4, "D", "SUPPORT",200));
listOfEmp.add(new Employee (5, "E", "SUPPORT",300));
listOfEmp.add(new Employee (6, "F", "SUPPORT",400));
listOfEmp.add(new Employee (7, "G", "IT",500));
listOfEmp.add(new Employee (8, "H", "IT",600));
listOfEmp.add(new Employee (9, "I", "IT",700));

以下是我写给按部门分组员工的查询

Map<String, List<String>> departmentWiseEmployees  = listOfEmp.stream().
        collect(Collectors.groupingBy(Employee::getDept, Collectors.mapping(Employee::getName, toList())));

我正在尝试使用以下方法使用以下方法查找每个部门中薪酬最高的 2 名员工。但它是

int limit = 2;
    Map<String, List<String>> groupByTeachers =
            listOfEmp.stream()
                    .collect(
                            Collectors.groupingBy(
                                    Employee::getDept,
                                    Collectors.collectingAndThen(
                                            Collectors.toList(),
                                            e -> e.stream().sorted().limit(limit).collect(toList() ) ) ) );

这里编译器抱怨提供的 lambda 参数出现以下错误collectingAndThen,它说 e 是类型List<Employee>,但它必须是List<Object>

在此处输入图像描述

有人可以帮助我了解这里出了什么问题吗?

标签: javalambdajava-8java-stream

解决方案


这部分代码:

e -> e.stream().sorted().limit(limit).collect(Collectors.toList())

返回 List of List<Employee>and not List<String>,因此您可以将结果的类型更改为:

Map<String, List<Employee>> groupByTeachers = 
                // ...The rest of your code

或者,如果您期望Map<String, List<String>>,更改collectingAndThen以获取期望的字段,例如getNamegetDep

e -> e.stream().sorted().limit(limit)
        .map(Employee::getDep) // for example getDep
        .collect(Collectors.toList())

推荐阅读