We have already discussed natural order comparators provided by JDK. This post will discuss natural order comparators provided by Apache Commons Collections library in Java.

The natural order comparator is useful when we want to sort a collection of objects that have a natural ordering, such as numbers, strings, dates, etc. The natural order is defined by the Comparable interface, which means that the objects to be compared must implement this interface. We can use the Apache Commons Collections to implement the natural comparators in Java. Some of the methods are:

1. Using naturalComparator() method

Apache Commons Collections ComparatorUtils class provides static naturalComparator() method that returns a comparator that uses the natural order of the objects. For example, we can use the natural order comparator to sort an array of strings as follows:

Download  Run Code

 
We can also use ComparatorUtils.NATURAL_COMPARATOR that provides a comparator for natural sort order of the objects. It is equivalent to ComparatorUtils.naturalComparator().

Download  Run Code

2. Using nullLowComparator() and nullHighComparator() method

If the array contains any null value, ComparatorUtils.naturalComparator() will throw a NullPointerException. The ComparatorUtils class provides static nullLowComparator() method to handle nulls. It returns a comparator that considers a null value to be less than any non-null value and equal to any other null value. The natural order of the objects is used when both of them are not null. For example:

Download  Run Code

 
The ComparatorUtils class also provides static nullHighComparator() method to handle nulls. It returns a comparator that considers a null value to be greater than any non-null value and equal to any other null value. For example:

Download  Run Code

3. Using NullComparator() constructor

Apache Commons Collections also provides NullComparator class whose instance will place null higher or lower than any non-null object it is compared with. We can create a NullComparator using the NullComparator() constructor that takes a boolean argument. This argument determines whether null values are higher or lower than non-null values. If it is true, null values are higher; if it is false, they are lower. The natural order of the objects is used when both of them are not null. For example:

Download  Run Code

That’s all about natural order comparators in Apache Commons Collections in Java.

 
Related Post:

Natural order comparators in Java by Guava’s Ordering class

 
References:

1. ComparatorUtils (Apache Commons Collections 4.1 API)

2. NullComparator (Apache Commons Collections 4.1 API)