Natural Comparators in Apache Commons Collections

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


 

Apache commons collections provides static ComparatorUtils.naturalComparator() that returns a comparator that uses the natural order of the objects.

Usage:

 
Apache commons collections also provides ComparatorUtils.NATURAL_COMPARATOR that provides a comparator for natural sort order of the objects.
It is equivalent to ComparatorUtils.naturalComparator().

Usage:

 
If specified array contains any null value, ComparatorUtils.naturalComparator() 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:

or

 

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:

or

 


 

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: Natural 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 code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 





Leave a Reply

Notify of
avatar
wpDiscuz