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<>().
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());
添加回答
举报
