4.5. Comparing Nulls
Problem
You need to sort an object array
that
contains null elements, and you want to have
control over whether the null values are at the
beginning or end of a sorted array.
Solution
Wrap your Comparator in a
NullComparator
from Commons Collections. The NullComparator can
sort null values higher or lower than
non-null values, depending on options passed into
the constructor. The following example shows a custom
BookComparator wrapped with a
NullComparator:
import org.apache.commons.collections.comparators.NullComparator; import java.util.*;Comparator bookComparator = new BookComparator( );Comparator nullComparator = new NullComparator( BookComparator );Book[] bookArray = new Book[] { new Book( ), null, new Book( ) }; Arrays.sort( bookArray, nullComparator );
This example sorts an array of Book objects,
placing null at the end of the sorted array; after
the sort, bookArray contains two
Book objects at index zero and index one and a
null reference at index two.
Tip
If a Comparator does not handle
null values gracefully, wrap it in a
NullComparator and avoid a
NullPointerException.
Discussion
To
configure NullComparator to sort null
values as less than non-null values,
pass false to the constructor of
NullComparator; to sort null
values as greater than non-null values, pass
true. By default, null values
are sorted higher:
// null is less than non-null Comparator nullComparator = new NullComparator( bookComparator, false ); // null is greater than non-null (default) ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access