This post will discuss reverse order comparators provided by JDK and implement our own reverse order comparators in Java. We will also cover how to handle null values in a Collection.

Comparators are the comparison functions applied to collections of objects to impose a total ordering on them. They can be passed to Collections.sort() or Arrays.sort() to allow precise control over the sort order.

We have already discussed natural order comparators in the previous post. Let’s discuss various reverse order comparators provided by JDK that compares objects in reverse order:

1. Using Comparator.reverseOrder() method

We can use static Comparator.reverseOrder() that returns a comparator that compares objects in reverse order. It imposes the reverse of the natural ordering.

Usage:

 
The above code will throw a NullPointerException if the specified array contains any null value. Java provides two methods to handle nulls:

1. Using nullsFirst()

Comparator‘s nullsFirst() method will put all null values before all non-null values and apply specified ordering to all non-null elements, as shown below:

2. Using nullsLast()

Comparator‘s nullsLast() method will put all null values after all non-null values and apply specified ordering to all non-null elements, as shown below:

2. Using Custom Comparators

We can also implement our own custom reverse order comparators:

Download  Run Code

Output:

[C, B, A]

 
We can convert the above code to use generics:

Download  Run Code

Output:

[C, B, A]

 
In Java 8 and above, we can also replace comparators with lambda expressions:

How can we handle nulls?

Like Comparator.reverseOrder(), the above code will throw a NullPointerException if the specified array contains any null value. We can easily modify the compare() method to handle nulls, as shown below:

1. To return a comparator that considers null to be less than non-null values:

 
2. To return a comparator that considers null to be greater than non-null values:

3. Using Guava Library

Google’s Guava library provides static Ordering.natural().reverse() that returns an Ordering that uses the reverse order of the values.

Reverse Order Comparator in Java using Guava’s Ordering class

4. Using Apache Commons Collections

Apache commons-collections provides static ComparatorUtils.reversedComparator() that returns a comparator that reverses the order of the specified comparator.

Reverse Order Comparators in Apache Commons Collections

That’s all about reverse order comparators in Java.

 
Reference: Comparator (Java Platform SE 8 )