Natural Comparators by Guava Ordering Class

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


 

Google’s Guava library provides static Ordering.natural() that returns an Ordering that uses the natural order of the values. Ordering is Guava’s Comparator class that has additional methods to support common operations not provided by JDK. It is preferred over Comparator.naturalOrder() before Java 8.

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 natural order comparators as shown below:

Java

Download   Run Code

Output:

[A, B, C]

Above code can be modified to use generics:

Java

Download   Run Code

Output:

[A, B, C]

 
How can we handle nulls?

Like Ordering.natural(), 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: Natural 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