Search code examples
java-8comparator

Comparator on list with only null value


The following code return Nullpointer exception:

Comparator<LocalDate> c = (LocalDate d1,LocalDate d2)-> {return (d1.isAfter(d2) ? 1 : (d1.isBefore(d2)? -1: 0));} ; 
List<LocalDate> list1 = new ArrayList<LocalDate>();
list1.add(null);
list1.add(null);
Optional<LocalDate> lastUsedDate = list1.stream()
                .max(Comparator.nullsLast(c));
System.out.println(lastUsedDate.get());

Can someone please help me understand how this can be resolved ?


Solution

  • As said, Stream#max does not allow null value as a result (so does not Stream#min).

    Throws:

    NullPointerException - if the maximum element is null

    The Stream API is not null-friendly, so neither reduce nor findFirst/findAny cooperate if the resulting element is null (not missing! but really null).

    You can do this:

    List<LocalDate> sortedList = new ArrayList<>(list1);
    sortedList.sort(Comparator.nullsLast(c));
    
    System.out.println(sortedList.get(sortedList.size() - 1));