gpt4 book ai didi

java - 如何获取 Iterable 集合中事件日期字段中事件日期最高的对象的唯一列表

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:19:41 27 4
gpt4 key购买 nike

我有一个 Iterable<Student> studentList其中包含具有字段 id、event_date 等的学生对象。

Iterable<Student> myStudentList (contains student objects);

现在这个学生列表包含一个学生 id 的许多对象。可以说我需要修改这个学生列表,使其只包含几个学生对象(每个学生 id 一个学生对象应该包含所有学生对象的最大 event_date 的 student_id )。我如何有效地做到这一点?

例如。目前列表包含以下项目

ListIndex  |  Student ID | Student Name | Student Event Date |
0 RV001 Mahesh 1328532774000
1 RV002 James 1328532774000
2 RV002 James 1454763174000
3 RV002 James 1549457671000
4 RV001 Mahesh 1549457671000
5 RV003 Andy 1454763174000

预期结果

现在我的结果 Iterable<Student>结果列表应包含以下内容

ListIndex  |  Student ID | Student Name | Student Event Date |
0 RV001 Mahesh 1549457671000
1 RV002 James 1549457671000
2 RV003 Andy 1454763174000

我如何使用 java 8 高效地实现这一点?

此数据来自按 event_date 分区的表

我目前能想到的方法:-P

Step 1 - Create a HashMap<Student_id, List<Student>>
Step 2 - Create a final List<Student> finalList for result purpose.
Step 2 - Iterate through the List<Student>
(a) For each student_id , store the list of Student objects in the
Map
-- END of Iterating List<Student>
Step 3 - Iterate Each Map Entry in HashMap
(a) For every key , Apply Comparator on List<Student> for
current student id.
(b) Get the first object of List<Student> in map for current
student_id and add it to the final list

如果您有更好的方法,请告诉我。

最佳答案

您可能只是在寻找类似的东西:

List<Student> finalList = students.stream()
// group by Id, value as List
.collect(Collectors.groupingBy(Student::getId,
// reduce the list of values to only one with greater event_date
Collectors.reducing((student, student2) ->
student.getEvent_date() > student2.getEvent_date() ? student : student2)))
.values() // stream only such values
.stream()
.map(Optional::get)
.collect(Collectors.toList()); // collect to list

或者正如 Holger 指出的那样,您可以使用

.collect(Collectors.toMap(Student::getId, Function.identity(), 
(s1, s2) -> s1.getEvent_date() > s2.getEvent_date() ? s1: s2))

这需要您将此处形成的 map 的值包装在 new ArrayList<>() 中.

关于java - 如何获取 Iterable<Student> 集合中事件日期字段中事件日期最高的对象的唯一列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54554229/

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