为了账号安全,请及时绑定邮箱和手机立即绑定

集合中的 event_date 字段中获取具有最高事件日期的对象的唯一列表

集合中的 event_date 字段中获取具有最高事件日期的对象的唯一列表

Helenr 2022-06-08 16:55:42
我有一个Iterable<Student> studentList包含字段 id、event_date 等等的学生对象。Iterable<Student> myStudentList (contains student objects);现在这个学生列表包含一个学生 id 的许多对象。假设我需要修改此学生列表,使其仅包含少数学生对象(每个学生 id 一个,并且该学生对象应包含其 student_id 的所有学生对象的最大 event_date )。我如何有效地做到这一点?例如。目前该列表包含以下项目ListIndex  |  Student ID | Student Name | Student Event Date |0            RV001         Mahesh          13285327740001            RV002         James           13285327740002            RV002         James           14547631740003            RV002         James           15494576710004            RV001         Mahesh          15494576710005            RV003         Andy            1454763174000预期结果现在我的结果Iterable<Student>列表应该包含以下结果ListIndex  |  Student ID | Student Name | Student Event Date |0            RV001         Mahesh          15494576710001            RV002         James           15494576710002            RV003         Andy            1454763174000我如何使用 java 8 有效地实现这一目标?此数据来自按 event_date 分区的表我目前能想到的方法:-PStep 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如果您有更好的方法,请告诉我。
查看完整描述

2 回答

?
肥皂起泡泡

TA贡献1829条经验 获得超6个赞

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


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

或者正如霍尔格指出的那样,您可以使用


.collect(Collectors.toMap(Student::getId, Function.identity(), 

                  (s1, s2) -> s1.getEvent_date() > s2.getEvent_date() ? s1: s2))

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


查看完整回答
反对 回复 2022-06-08
?
慕森王

TA贡献1777条经验 获得超3个赞

与@nullpointer 答案类似,但假设事件日期有或类型,您可以使用int下游with或比较器longdoublemaxBycomparingIntcomparingLongcomparingDouble

studentList.stream()
    .collect(groupingBy(Student::getId, 
             maxBy(Comparator.comparingLong(Student::getEventDate))))
    .values()
    .stream()
    .map(Optional::get)
    .collect(toList());


查看完整回答
反对 回复 2022-06-08
  • 2 回答
  • 0 关注
  • 159 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号