Comparator.nullsLast does not avoid NullPointerException

You can possibly use :

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

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())));