How to apply sorting and limiting after groupby using Java streams

后端 未结 3 741
[愿得一人]
[愿得一人] 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-15 20:04

    This part of code:

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

    return List of List and not List, so either you change the type of the result to:

    Map> groupByTeachers = 
                    // ...The rest of your code
    

    Or if you expect Map>, change the collectingAndThen to get the expected field, for example getName or getDep:

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

提交回复
热议问题