Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparator.nullsLast does not avoid NullPointerException

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?

like image 398
rellocs wood Avatar asked Nov 15 '18 07:11

rellocs wood


People also ask

What can help us in avoiding Nullpointerexception?

Java 8 introduced an Optional class which is a nicer way to avoid NullPointerExceptions. You can use Optional to encapsulate the potential null values and pass or return it safely without worrying about the exception. Without Optional, when a method signature has return type of certain object.

How do you handle null in comparator?

Comparator nullsLast() method in Java with examples When both elements are null, then they are considered equal. When both elements are non-null, the specified Comparator determines the order. If specified comparator is null, then the returned comparator considers all non-null elements equal.


1 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()))); 
like image 188
ETO Avatar answered Sep 23 '22 11:09

ETO