问题描述
我有如下的学生对象列表。
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对学生进行分组。
- 所有学生应根据学生姓名分组。
- 学生必须按dob降序排列。
- 同一学生分组 在一起应该按dob降序排列。
- 剩余的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 (将#修改为@)