简体   繁体   中英

Sorting a list of objects based on a nullable ArrayList attribute of that object using java 8

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()); 

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()); 

You should try something like this :

    Optional.ofNullable(list).map(list - > list.stream().filter(property == null)).orElse(null);

So that you dont try to use .steam() on a null Object.

您可以使用本机 Java >= 8 方法

Collections.sort(/*list name*/visits, /*elements from list*/(l, r) -> /*example logic*/l.date.compareTo(r.date));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM