We have already discussed the reverse order comparators provided by JDK in the previous post. This post will discuss the reverse order comparators provided by Apache commons-collections in Java.

Apache commons-collections provides static ComparatorUtils.reversedComparator() that returns a comparator that reverses the order of the specified comparator. Since we want a reverse order comparator, we can pass any Natural Order Comparator to it.

Usage:

 
We can also call Comparator.reversed() on ComparatorUtils.NATURAL_COMPARATOR to get comparator that imposes the reverse ordering. It is equivalent to calling Collections.reverseOrder(ComparatorUtils.NATURAL_COMPARATOR).

Usage:

 
If the specified array contains any null value, ComparatorUtils.reversedComparator() will throw a NullPointerException. Apache commons-collections provides two methods to handle nulls:

1. Using nullLowComparator() method

ComparatorUtils class provides static nullLowComparator() method that returns a comparator that considers a null value to be less than any non-null value and equal to any other null value:

2. Using nullHighComparator() method

ComparatorUtils class also provides static nullHighComparator() method that returns a comparator that considers a null value to be greater than any non-null value and equal to any other null value:

 
Apache commons-collections also provides NullComparatorclass whose instance will sort null higher or lower than any non-null object it is compared with.

⮚ Nulls at the beginning

⮚ 2. Nulls at the end

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

 
Related Post:

Reverse Order Comparator in Java using Guava’s Ordering class

 
References: