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或比較器long
double
maxBy
comparingInt
comparingLong
comparingDouble
studentList.stream() .collect(groupingBy(Student::getId, maxBy(Comparator.comparingLong(Student::getEventDate)))) .values() .stream() .map(Optional::get) .collect(toList());
添加回答
舉報