…unless we try to sort a collection containing null values:
Fortunately there is easy solution to this problem. But first we must
decide whenever we want nulls to be first or last in sorted collection.
After we made our mind we may use nifty nullsFirst or nullsLast
decorators provided by Comparator interface:
nullsFirst is great example of decorator design pattern
(it adds functionality but doesn’t change interface).
nullsFirst works by wrapping provided comparator in code similar to:
Previous example works great unless we try to sort a collection
But do not despair nullsFirst can help us again:
Ta da! It works but readability suffers greatly… You may ask what is
First: we use the following overload of comparing method:
Second: in our example nullsFirst(naturalOrder()) is a comparator that can
compare nullable Strings:
Now everything should be clear (I hope).
To sum up in this post we get to know two
little methods nullsFirst and nullsLast.
I admit that they are a bit unintuitive to use, but definitely worth
to bear in mind.