1

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 ?

3
  • 2
    The javadoc of max says: throws NullPointerException if the maximum element is null. If you want to avoid that, you can filter out the null elements from the stream, but in that case you won't need to use Comparator.nullsLast(). Commented Feb 29, 2024 at 7:06
  • 1
    To perhaps clarify, the comparator in your example is not the problem. The NPE is not being thrown by the comparator. You could sort the list with that comparator without issue. The problem is that the maximum element ends up being null, and Stream::max can't handle that. That method returns Optional which can't represent null as a non-empty result. It also can't just return an empty optional because "empty" means "no value", yet there was a value: null. Hence the NPE. Commented Feb 29, 2024 at 7:35
  • Thanks for the help @Eran and Slaw for the solution and explanation Commented Mar 20, 2024 at 5:43

1 Answer 1

0

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));
Sign up to request clarification or add additional context in comments.

2 Comments

Or without an expensive sorting: LocalDate max = Collections.max(list1, Comparator.nullsLast(Comparator.naturalOrder()));
Oh yes, that’s smart.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.