I am trying to sort a list based on a nullable ArrayList in java 8.
List 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());