需要对学生列表使用分组、排序和限制,从而返回学生列表

问题描述 投票:0回答:1
class Student{
    private String name;  
    private String id; 
    private String dept;  
    private String sub;  
    private double marks; 
}

需要根据部门对学生列表进行分组,然后根据分数排序,然后显示前 2 名学生 试过这个-

Map<String,List<Student>> studlistGrouped = list.stream().collect(Collectors.groupingBy(Student::getDept,Collectors.toList()));
List<Student> sorted = studlistGrouped.entrySet().stream()
            .sorted(Comparator.comparing(e ->  e.getValue().stream().map(Student::getId).min(Comparator.naturalOrder()).orElse(0)))
            //and also sort each group before collecting them in one list
            .flatMap(e ->  e.getValue().stream().sorted(Comparator.comparing(Student::getId))).collect(Collectors.toList());

但显示 e.getValue() 的编译错误

java sorting limit
1个回答
0
投票

要获取每个系的前 2 名学生(按分数降序排列):

前两行与您所做的相同,即按部门对每个学生进行分组。

从结果映射(类型为

Map<String, List<Student>>
)中,这会从
Map#entrySet
创建另一个流,并使用
Collectors.toMap
收集到另一个映射中。 keyMapper
toMap
的第一个参数)将部门设置为键。在 valueMapper
toMap
的第二个参数)中,它对所有学生进行流式传输,并按分数以相反的顺序对他们进行排序,并限制为前 2 位学生,然后将他们收集为列表。

Map<String, List<Student>> result = list.stream()
        .collect(Collectors.groupingBy(Student::getDept, Collectors.toList()))
        .entrySet()
        .stream()
        .collect(Collectors.toMap(Map.Entry::getKey,
                e -> e.getValue()
                        .stream()
                        .sorted(Comparator.comparingDouble(Student::getMarks).reversed())
                        .limit(2)
                        .collect(Collectors.toList())));
© www.soinside.com 2019 - 2024. All rights reserved.