问题
I have a list of Student Objects as below.
Student1 DOB : 12/02/2010
Student2 DOB : 12/03/2010
Student1 DOB : 12/04/2010
Student4 DOB :
Student2 DOB :
Student3 DOB : 12/01/2010
Student{
String name;
Date dob;
}
I want to group the Students based on the DOB as below.
- All Students should be grouped based on the student name.
- Students must be in descending order of dob.
- Same Students grouped together should be in descending order of dob.
- Remaining Student objects must be in same order as it is there in the input list
Like,
Student1 DOB : 12/04/2010
Student1 DOB : 12/02/2010
Student2 DOB : 12/03/2010
Student2 DOB :
Student3 DOB : 12/01/2010
Student4 DOB :
I found a matching solution here Sorting and Grouping on a list of objects , but it won't work if dob is null. Is there any work around in java8 using streams?
As per the above link step 1, I have tried
Map<String, Optional<Student>> students = students.stream()
.collect(Collectors.groupingBy(
Student::getName,
Collectors.maxBy(Comparator.comparing(o -> o.getDob()))));
Here getDob() can return null sometimes and throws null pointer exception. Filter won't be a solution as it will totally avoid Students with dob as null.
来源:https://stackoverflow.com/questions/63884675/groupingby-a-list-of-objects-based-on-an-attribute-which-can-be-null