4.3. Reversing a Comparator
Problem
You need to reverse the effects
of
a Comparator. You need to return less than when
this Comparator returns greater than, and greater
than when it returns less than.
Solution
Use
ReverseComparator
to reverse the effects of a Comparator. Supply an
existing Comparator to the constructor of
ReverseComparator, and it reverses the effects of
that Comparator. The following example
demonstrates the use of ReverseComparator to
reverse the result of a custom MyComparator
instance:
Comparator myComparator = new MyComparator( );Comparator reverseComparator = new ReverseComparator( myComparator );Book book1 = new Book( ); Book book2 = new Book( ); int comparison = myComparator.compare( book1, book2 );int reversedComparison = reverseComparator( book1, book2);
The value of reversedComparison is simply the
negative of comparison; if
MyComparator decides that book1
is less than book2, the
ReverseComparator returns the opposite
result—greater than. ReverseComparator
simply wraps the original Comparator and
multiplies the result by negative one.
Discussion
Example 4-1 is an implementation of a
Comparator that is reversed using the
ReverseComparator. This
BookComparator compares two
Book objects by the name and
author bean properties. Sorting a list of books
using this Comparator results in a list sorted
alphabetically by book name and author name; if two books have the
same name, they are sorted by author name.
Example 4-1. A Comparator that compares Book objects ...
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