We have discussed natural order comparators provided by JDK in the previous post. This post will discuss natural order comparators provided by Guava Ordering class in Java.

The Ordering class is part of the Guava library and can be used to create and use comparators in Java. The Ordering class implements the Comparator interface, but also provides many additional methods to support common operations, such as sorting, filtering, finding minima and maxima, and more.

1. Using Ordering.natural() method

Guava library provides the static Ordering.natural() method that returns an Ordering object which uses the natural order of the values to compare them. This method is preferred over Comparator.naturalOrder() before Java 8. Here is an example of how we can use this method to sort an array in natural order:

Download Code

 
The above code will throw a NullPointerException if the specified array contains any null value. The Guava Ordering class provides nullsFirst() method which returns an ordering that considers null to be less than non-null values. For example:

Download Code

 
Note how we can chain different Ordering instances together to create comparators that can handle null values. We can also use the nullsLast() method, which returns an ordering that considers null to be greater than non-null values. For example:

Download Code

2. Using Custom Ordering

We can also write our own custom natural order comparators by extending the Ordering class and overriding its compare() method. To illustrate, consider the following example which creates a custom natural order comparator using the Ordering class:

Download Code

 
Like Ordering.natural(), the above implementation will throw a NullPointerException if the array contains any null value. To return an Ordering that considers null to be less than non-null values, we can modify the compare() method like below:

Download Code

 
Similarly, to return an Ordering that considers null to be greater than non-null values, we can modify the compare() method like below:

Download Code

That’s all about natural order comparators by Guava’s Ordering class.

 
Related Post:

Natural order comparators in Java by Apache Commons Collections

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