I\'m writing some custom Comparators, and I\'d like them to push null items to the bottom of the list, regardless of whether I\'m sorting ascending or descending. What\'s a
In Java 8, you can use the Comparator.nullsLast and Comparator.nullsFirst static methods to have more null-friendly comparators. Suppose you have a Fruit class like the following:
public class Fruit {
private final String name;
private final Integer size;
// Constructor and Getters
}
If you want to sort a bunch of fruits by their size and put the nulls at the end:
List fruits = asList(null, new Fruit("Orange", 25), new Fruit("Kiwi", 5));
You can simply write:
Collections.sort(fruits, Comparator.nullsLast(Comparator.comparingInt(Fruit::getSize)));
And the result would be:
[Fruit{name='Kiwi', size=5}, Fruit{name='Orange', size=25}, null]