How to handle nulls when using Java collection sort

Giancarlo Corzo picture Giancarlo Corzo · Sep 8, 2010 · Viewed 45.5k times · Source

When using Collection.sort in Java what should I return when one of the inner objects is null

Example:

Collections.sort(list, new Comparator<MyBean>() {
    public int compare(MyBean o1, MyBean o2) {
      return o2.getDate().compareTo(o1.getDate());
     } 

});

Lets say o2 is not null but o2.getDate() it is, so should I return 1 or -1 or 0 when adding a null validation?

Answer

Nikita Rybak picture Nikita Rybak · Sep 8, 2010

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