How to handle nulls when using Java collection sort

In Java 8 you can also use nullsFirst():

Comparator.nullsFirst(Date::compareTo).compare(dateOne, dateTwo);

Or nullsLast():

Comparator.nullsLast(Date::compareTo).compare(dateOne, dateTwo);

These methods will either sort null to the beginning or to the end. There is no wrong or right whether you consider null bigger or smaller than another objects. This is totally up to you, as others stated already.


Naturally, it's your choice. Whatever logic you write, it will define sorting rules. So 'should' isn't really the right word here.

If you want null to appear before any other element, something like this could do

public int compare(MyBean o1, MyBean o2) {
    if (o1.getDate() == null) {
        return (o2.getDate() == null) ? 0 : -1;
    }
    if (o2.getDate() == null) {
        return 1;
    }
    return o2.getDate().compareTo(o1.getDate());
}