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?
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.
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.
You should use Comparator.nullsLast
twice:
list.sort(nullsLast(comparing(Bean::getVal, nullsLast(naturalOrder()))));
nullsLast
will handle the cases when the Bean
objects are null.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())));
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