gpt4 book ai didi

Java 使用 Stream 对列表进行排序和分组

转载 作者:行者123 更新时间:2023-12-02 02:02:57 25 4
gpt4 key购买 nike

我有一个List<Records> =

[
{"studentId": "001", "date": "20180705", "courseId": "CS220", "score": "80"},
{"studentId": "001", "date": "20180702", "courseId": "CS320", "score": "75"},
{"studentId": "001", "date": "20180704", "courseId": "CS330", "score": "90"},

{"studentId": "002", "date": "20180703", "courseId": "CS640", "score": "95"},
{"studentId": "002", "date": "20180628", "courseId": "CS530", "score": "80"},
{"studentId": "002", "date": "20180701", "courseId": "CS545", "score": "90"},

{"studentId": "100", "date": "20180708", "courseId": "CS542", "score": "80"},
{"studentId": "100", "date": "20180629", "courseId": "CS240", "score": "97"},

...
]

如何按相同的 studentId 对对象进行分组并只保留列表中得分最高的那个?像下面这样: List<Records> =

[
{"studentId": "001", "date": "20180704", "courseId": "CS330", "score": "90"},

{"studentId": "002", "date": "20180703", "courseId": "CS640", "score": "95"},

{"studentId": "100", "date": "20180629", "courseId": "CS240", "score": "97"},

...
]

最佳答案

使用Stream来收集值。您可以在 Baeldung -- Guide to Java 8 groupingBy Collector 上找到示例

2.8. Getting the Maximum or Minimum from Grouped Results

这可以像这样使用:

records.stream()
.collect(
Collectors.groupingBy(
Record::getStudentId,
Collectors.maxBy(Compartor.comparingInt(Record::getPoint))
)
);

返回的映射将以每个 studentId 作为键以及具有最大值的实例。使用 POJO 的示例:

class POJO {
String name;
int value;

//getters
//toString //POJO [%name% %value%]
}

快速测试:

Map<String, Optional<POJO>> map = Stream.of(
new POJO("A", 1), new POJO("A", 2), new POJO("A", 10),
new POJO("B", 8), new POJO("B", 4),
new POJO("C", 4),
new POJO("D", 4), new POJO("D", 1), new POJO("D", 2)
).collect(
Collectors.groupingBy(
POJO::getName,
Collectors.maxBy(
Comparator.comparingInt(POJO::getValue)
)
)
);

System.out.println(map);

{A=Optional[POJO [A 10]],
B=Optional[POJO [B 8]],
C=Optional[POJO [C 4]],
D=Optional[POJO [D 4]]}

关于Java 使用 Stream 对列表进行排序和分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51287280/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com