Reverse Order Comparators in Apache Commons Collections

We have already discussed reverse order comparators provided by JDK in previous post. In this post, we will discuss reverse order comparators provided by Apache commons collections.


 

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 specified array contains any null value, ComparatorUtils.reversedComparator() will throw a NullPointerException. Apache commons collections provides two methods to handle nulls –

 

1. nullLowComparator()

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

 

2. nullHighComparator()

ComparatorUtils class also provides static nullHighComparator() method that returns a comparator that consider 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 sorts null higher or lower than any non-null object it is compared with.

1. Nulls in beginning

 
2. Nulls in the end

 
 
Related Posts: Reverse Order Comparator by Guava Ordering Class

 
References:

1. ComparatorUtils (Apache Commons Collections 4.1 API)

2. NullComparator (Apache Commons Collections 4.1 API)

 
Thanks for reading.

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





Leave a Reply

Notify of
avatar
wpDiscuz