How to apply sorting and limiting after groupby using Java streams

后端 未结 3 740
[愿得一人]
[愿得一人] 2021-01-15 19:30

I have the following list of Employee data which I need to group based on the employee department and then I want to find the 2 highest-paid employees in each department.

3条回答
  •  北荒
    北荒 (楼主)
    2021-01-15 20:12

    Here is the final answer for those who are interested.

    Map> groupByTeachers =
            listOfEmp.stream()
                    .collect(
                            Collectors.groupingBy(
                                    Employee::getDept,
                                    Collectors.collectingAndThen(
                                            Collectors.toList(),
                                            e -> e.stream().sorted(Comparator.comparingLong(Employee::getSalary).reversed()).limit(limit).map(Employee::getName).collect(toList() ) ) ) );
    

提交回复
热议问题