Reverse Order Comparator by Guava Ordering Class

We have already discussed reverse order comparator provided by JDK in previous post. In this post, we will discuss reverse order comparator provided by Guava Ordering Class.


 

Google’s Guava library provides Ordering.natural() that returns an Ordering that uses the natural order of the values. We can use Ordering.natural().reverse() that returns an Ordering which uses the reverse order of the values. Ordering is Guava’s Comparator class that has additional methods to support common operations not provided by JDK.

Usage:

 
Above code will throw a NullPointerException if specified array contains any null value. Guava provides two methods to handle nulls –

1. nullsFirst()

Guava Ordering class provides nullsFirst() method that returns a ordering that considers null to be less than non-null values as shown below:

 

2. nullsLast()

Guava Ordering class also provides nullsLast() method that returns a ordering that considers null to be greater than non-null values as shown below:

 
We can also write our own custom reverse order comparator as shown below:

Java

Download   Run Code

Output:

[C, B, A]

Above code can be modified to use generics:

Java

Download   Run Code

Output:

[C, B, A]

 
How can we handle nulls?

Above custom implementation will throw a NullPointerException if specified array contains any null value. We can easily modify compare() function to handle nulls:

1. To return an Ordering that considers null to be less than non-null values –

 
2. To return an Ordering that considers null to be greater than non-null values –

 
 
Related Posts: Reverse Order Comparators in Apache Commons Collections

 
References: Ordering (Guava: Google Core Libraries for Java 21.0 API)

 
Thanks for reading.




Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 





Leave a Reply

Notify of
avatar
wpDiscuz