Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 - Sort list of integers with nulls

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!

like image 906
Bogdan Avatar asked Sep 07 '25 10:09

Bogdan


1 Answers

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.

like image 122
Eugene Avatar answered Sep 10 '25 08:09

Eugene