When using Collection.sort in Java what should I return when one of the inner objects is null
Example:
Collections.sort(list, new Comparator
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.