英文:
Sorting a list of objects based on a nullable ArrayList attribute of that object using java 8
问题
以下是翻译好的内容:
我正尝试根据 Java 8 中的可为空 ArrayList 对列表进行排序。
列表如下所示:
Patient1 visits = [02/15/2010, 02/10/2010]
Patient2 visits = [02/16/2010]
Patient3 visits = [02/17/2010, 02/10/2010]
Patient4 visits = null
我试图使用流式排序根据就诊日期(访问列表中的第一个元素)的降序对患者对象进行排序。空值应该排在最后。最终结果应为
Patient3 visits = [02/17/2010, 02/10/2010]
Patient2 visits = [02/16/2010]
Patient1 visits = [02/15/2010, 02/10/2010]
Patient4 visits = null
Patient 类如下:
class Patient {
String name;
List<Date> visits;
}
我尝试了以下方法,但仍然出现空指针异常,即使进行了空值检查。
list.stream()
.sorted(Comparator.nullsLast((Comparator.comparing(s -> s.getVisits() == null ? null : s.getVisits().get(0), Collections.reverseOrder()))))
.collect(Collectors.toList());
英文:
I am trying to sort a list based on a nullable ArrayList in java 8.
List<Patient> as follows
Patient1 visits = [02/15/2010, 02/10/2010]
Patient2 visits = [02/16/2010]
Patient3 visits = [02/17/2010, 02/10/2010]
Patient4 visits = null
I am trying to sort the Patient objects based on the descending order of their date of visit (first element in the visits list) using streams sort. The nulls should be placed last. The final result must be
Patient3 visits = [02/17/2010, 02/10/2010]
Patient2 visits = [02/16/2010]
Patient1 visits = [02/15/2010, 02/10/2010]
Patient4 visits = null
Patient {
String name;
List<Date> visits;
}
I have tried the following approach but ends up in null pointer exception even after null check.
list.stream()
.sorted(Comparator.nullsLast((Comparator.comparing(s -> s.getVisits() == null ? null : s.getVisits().get(0), Collections.reverseOrder()))))
.collect(Collectors.toList());
答案1
得分: 3
你所面临的问题是,如果您有null
的Patient
对象,将会使用Comparator.nullsLast
。但这不是您的情况,因为您有null
的访问记录。
您应该这样使用:
list.stream()
.sorted(Comparator.comparing(
s -> s.getVisits() == null || s.getVisits().isEmpty() ?
null :
s.getVisits().get(0),
Comparator.nullsLast(Collections.reverseOrder())))
.collect(Collectors.toList());
英文:
The problem you are facing is that Comparator.nullsLast
would be used if you had null
Patient
objects. This is not your case, because you have null
visits.
You should use it this way:
list.stream()
.sorted(Comparator.comparing(
s -> s.getVisits() == null || s.getVisits().isEmpty() ?
null :
s.getVisits().get(0),
Comparator.nullsLast(Collections.reverseOrder())))
.collect(Collectors.toList());
答案2
得分: 0
你可以使用Java 8或更高版本的本地方法:
Collections.sort(/*列表名称*/ visits, /*从列表中选择的元素*/ (l, r) -> /*示例逻辑*/ l.date.compareTo(r.date));
英文:
You could use a native Java >= 8 method
Collections.sort(/*list name*/visits, /*elements from list*/(l, r) -> /*example logic*/l.date.compareTo(r.date));
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论