We have already discussed the reverse order comparator provided by JDK in the previous post. This post will discuss the reverse order comparator provided by Guava Ordering class in Java.

Guava’s Ordering class allows us to build complex comparators and apply them to collections of objects. It also provides many useful methods to sort, filter, and manipulate data based on the ordering. Basically Ordering is Guava’s Comparator class with additional methods to support common operations not provided by JDK.

1. Using Ordering.natural().reverse() method

Guava’s Ordering class is a powerful and flexible way to chain comparators in Java. It provides the natural() method that returns an Ordering object that uses the natural order of the values and the reverse() method that returns an Ordering object that uses the reverse order of the original Ordering. Therefore, we can use Ordering.natural().reverse() to get an ordering that uses the reverse of the natural order of the values. We can use this Ordering object to sort collections in reverse order. For example, we can sort an array of strings in reverse order like this:

Download Code

 
The above code will throw a NullPointerException if the specified array contains any null value. We can handle nulls using the nullsFirst() method that returns an ordering that considers null to be less than non-null values, as shown below:

Download Code

 
Alternatively, we can use the nullsLast() method that returns an ordering that considers null to be greater than the non-null values, as shown below:

Download Code

2. Using Custom Ordering

Guava’s Ordering class implements the Comparator interface and provides many methods to customize the ordering of objects. We can also create a custom reverse order comparator by extending the Ordering class and overriding the compare() method to implement our own logic for reversing the order. Here is an example of how to create a custom reverse order comparator using Guava’s Ordering class:

Download Code

 
The above custom implementation will throw a NullPointerException if the specified array contains any null value. We can easily modify the compare() method to handle nulls. For example, consider the following generic version, that returns an Ordering that considers null to be less than non-null values:

Download Code

 
To return an Ordering that considers null to be greater than non-null values, we can do like:

Download Code

That’s all about reverse order comparators provided by Guava’s Ordering class in Java.

 
Related Post:

Reverse Order Comparators in Apache Commons Collections

 
Reference: Ordering (Guava: Google Core Libraries for Java 31.0-jre API)