Lets say you have a list of integers containing null vaues
List<Integer> integers = Arrays.asList(null, 9, 11, 7, 5, null);
Now if you want to get max value, you can try
OptionalInt max = integers.stream()
.mapToInt(Integer::valueOf)
.max();
This would work if the list did not contain nulls. In our case there will be a NullPointerException. After some research I can see such solution
Optional<Integer> max = integers.stream()
.max(Comparator.nullsFirst(Comparator.naturalOrder()));
It works if you consider nulls less then non-nulls. But if you want them to be greater and change nullsFirst to nullsLast
Optional<Integer> max = integers.stream()
.max(Comparator.nullsLast(Comparator.naturalOrder()));
then you will meet NullPointerException again.
I am interesting - why nullsLast doesn't work in this case considering that its doc states that it is null-friendly? And what is the best way to sort list of Integers containing nulls?
Thanks for your ideas!