Comparator.nullsLast does not avoid NullPointerException

Viewed 16259

I want to sort a list of objects by one of nullable fields.

In order to avoid NullPointerexception I use Comparator.nullsLast. But the exception still occurs:

public class Test {

    public static void main(String[] args) {
        List<Bean> l = new ArrayList<>();
        for (int i=0;i<5;i++) {
            Bean b = new Bean("name_"+i,i);
            l.add(b);
        }
        l.get(2).setVal(null);
        System.out.println(l);
        Collections.sort(l, Comparator.nullsLast(Comparator.comparing(Bean::getVal)));
        System.out.println(l);
    }

    static class Bean{
        String name;
        Integer val;
        // omit getters & setters & constructor
    }

}

How can I sort this kind of list?

3 Answers

You should use Comparator.nullsLast twice:

list.sort(nullsLast(comparing(Bean::getVal, nullsLast(naturalOrder()))));
  • First nullsLast will handle the cases when the Bean objects are null.
  • Second nullsLast will handle the cases when the return value of Bean::getVal is null.

In case you're sure there aren't any null values in your list then you can omit the first nullsLast (as noted by @Holger) :

list.sort(comparing(Bean::getVal, nullsLast(naturalOrder())));

You can possibly use :

Collections.sort(l, Comparator.comparing(Bean::getVal,
                              Comparator.nullsLast(Comparator.naturalOrder())));

You can review this example

@Override
public int compare(Example o1, Example o2) {
  if (o1 == null && o2 == null) return 0;
  if (o1 == null) return -1;
  if (o2 == null) return 1;
 return Comparator.comparing(Example::getSta,
      Comparator.nullsLast(Comparator.naturalOrder()))
      .thenComparing(Example::getId,
          Comparator.nullsLast(Comparator.naturalOrder()))
      .compare(o1, o2);
}

class Example {
String sta; Long id;}
Related