Carl Manaster Carl Manaster - 5 months ago 17
Java Question

Nice general way to sort nulls to the bottom, regardless?

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 good strategy or pattern for approaching this?


  • simply write separate ascending and
    descending comparators, sharing code
    where possible;

  • delegate null handling to another
    class, either by throwing an NPE or
    by calling it explicitly;

  • include an ascending flag and put
    conditional logic in it to navigate
    around the nulls.

  • Wrap regular comparators in a
    null-handling class

Any others? I'd like to hear about any experiences with different approaches, any pitfalls for the various strategies.


The last option appeals to me a lot. Comparators are really great to chain together. In particular you may well want to write a ReverseComparator as well as a NullWrappingComparator.

EDIT: You don't have to write this yourself. If you look at the Ordering class in the Google Collections Library you'll find this and all kinds of other goodies :)

EDIT: Going into more detail to show what I mean about ReverseComparator...

One word of warning - in the implementation of a ReverseComparator, reverse the order of the arguments instead of negating the result, as otherwise Integer.MIN_VALUE is "reversed" to itself.

So this implementation is wrong (assuming original is the comparator to reverse):

public int compare(T x, T y)
    return, y);

but this is right:

public int compare(T x, T y)
    return, x);

The reason is that we always want to reverse the comparison, but if, y) returns int.MIN_VALUE, then the bad comparer will also return int.MIN_VALUE, which is incorrect. This is due to the funny property that int.MIN_VALUE == -int.MIN_VALUE.