根据可以为空的属性按对象列表分组

问题描述

我有如下的学生对象列表。

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;
}

我想按以下dob对学生进行分组。

  1. 所有学生应根据学生姓名分组。
  2. 学生必须按dob降序排列。
  3. 同一学生分组 在一起应该按dob降序排列。
  4. 剩余的Student对象必须与输入列表中的对象顺序相同

就像

    Student1  dob : 12/04/2010
    Student1  dob : 12/02/2010
    Student2  dob : 12/03/2010
    Student2  dob : 
    Student3  dob : 12/01/2010
    Student4  dob : 

在这里Sorting and Grouping on a list of objects找到了匹配的解决方案 ,但如果dob为null,则它将不起作用。在java8中使用流可以解决任何问题吗?

按照上面的链接第1步,我已经尝试

Map<String,Optional<Student>> students = students.stream()
    .collect(Collectors.groupingBy(
             Student::getName,Collectors.maxBy(Comparator.comparing(o -> o.getdob()))));

在这里,getdob()有时可以返回null并引发null指针异常。过滤器不是解决方案,因为它将完全避免dob为null的学生。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)