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!
That's not about Comparator
per-se:
List<Integer> result = integers.stream()
.sorted(Comparator.nullsLast(Comparator.naturalOrder()))
.collect(Collectors.toList());
System.out.println(result); // [5, 7, 9, 11, null, null]
You are putting your nulls to the end and that would be max
; calling max
on a null throws that NullPointerException
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With