Java Reference
In-Depth Information
Using a
Comparator
is easy. Create its object and pass it to the methods that take a collection of objects and
a comparator to compare them. For example, to sort an array of
ComparablePerson
objects, pass the array and a
FirstNameComparator
to the static
sort()
method of the
Arrays
class.
ComparablePerson[] persons = create and populate the array...
// Sort the persons array based on first name
Comparator fnComparator = new FirstNameComparator();
Arrays.sort(persons, fnComparator);
You can use a similar logic to sort the array based on the last name.
// Sort the persons array based on last name
Comparator lnComparator = new LastNameComparator();
Arrays.sort(persons, lnComparator);
Prior to Java 8, if you wanted to the array based on the first name followed by the last name, you needed to create
another implementation of the
Comparator
interface. Thanks to Java 8's adding of default methods to interfaces,
you do not need to create a new implementation of the
Comparator
interface. The
Comparator
class contains a
thenComparing()
default method declared as follows:
default Comparator<T> thenComparing(Comparator<? super T> other)
The
thenComparing()
method takes a
Comparator
as an argument and returns a new
Comparator
. The new
Comparator
is used for ordering if the two objects being compared are equal using the original
Comparator
. The
following snippet of code combines the first name and last
Comparators
to create a new
Comparator
:
// Sort using first name, then last name
Comparator firstLastComparator = fnComparator.thenComparing(lnComparator);
Arrays.sort(persons, firstLastComparator);
■
You can chain the call to the
thenComparing()
method to create a
Comparator
that imposes the ordering on
several nested levels.
Tip
There is another useful addition to the
Comparator
interface in Java 8: a default method named
reversed()
.
The method returns a new
Comparator
that imposes the reverse ordering of the original
Comparator
. If you want to
sort the array of persons based on first name, then last name in descending order, you can do so as follows:
// Sort using first name, then last name in reversed order
Comparator firstLastReverseComparator = firstLastComparator.reversed();
Arrays.sort(persons, firstLastReverseComparator);
Comparators
do not handle null values well. Typically, they throw a
NullPointerException
. Java 8 added two
useful, null-friendly, convenience static methods to the
Comparator
interface.
static <T> Comparator<T> nullsFirst(Comparator<? super T> comparator)
•
static <T> Comparator<T> nullsLast(Comparator<? super T> comparator)
•