简体   繁体   English

使用 java 8 根据该对象的可为空的 ArrayList 属性对对象列表进行排序

[英]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.我正在尝试根据 java 8 中的可为空的 ArrayList 对列表进行排序。

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.我正在尝试使用流排序根据访问日期(访问列表中的第一个元素)的降序对 Patient 对象进行排序。 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.您面临的问题是Comparator.nullsLast如果您有null Patient对象将被使用。 This is not your case, because you have null visits.这不是你的情况,因为你null访问。

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.这样您就不会尝试在空对象上使用 .steam() 。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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