Groupingby a list of objects based on an attribute which can be null

不羁岁月 提交于 2021-02-20 00:50:36

问题


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.

  1. All Students should be grouped based on the student name.
  2. Students must be in descending order of dob.
  3. Same Students grouped together should be in descending order of dob.
  4. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!