Reverse Order Comparators in Java

In this post, we will cover reverse order comparators provided by JDK and also implement our own reverse order comparators. We will also cover how to handle null values in a Collection.


 

Comparators are the comparison functions that can be applied to collections of objects to impose a total ordering on them. They can be passed to Collections.sort() or Arrays.sort() to allow precise control over the sort order.

We have already discussed natural order comparators in previous post. Let’s discuss various reverse order comparators provided by JDK that compares objects in reverse order –

 

1. Comparator.reverseOrder()

We can use static Comparator.reverseOrder() that returns a comparator that compares objects in reverse order. It imposes the reverse of the natural ordering.

Usage:

 
Above code will throw a NullPointerException if specified array contains any null value. Java provides two methods to handle nulls –

 

1. nullsFirst()

Comparator‘s nullsFirst() method will put all null values before all non-null values and apply specified ordering to all non-null elements as shown below:

 

2. nullsLast()

Comparator‘s nullsLast() method will put all null values after all non-null values and apply specified ordering to all non-null elements as shown below:

 

2. Custom Comparators

We can also implement our own custom reverse order comparators:

Java

Download   Run Code

Output:

[C, B, A]

Above code can be converted to use generics:

Java

Download   Run Code

Output:

[C, B, A]

In Java 8 and above, we can also replace comparators by Lambda expressions –

 
How can we handle nulls?

Like Comparator.reverseOrder(), above code will throw a NullPointerException if specified array contains any null value. We can easily modify compare() function to handle nulls as shown below:

1. To return a comparator that considers null to be less than non-null values –

2. To return a comparator that considers null to be greater than non-null values –

 

3. Guava

Google’s Guava library provides static Ordering.natural().reverse() that returns an Ordering that uses the reverse order of the values.

Read: Reverse Order Comparator by Guava Ordering Class

 

4. Apache commons collections

Apache commons collections provides static ComparatorUtils.reversedComparator() that returns a comparator that reverses the order of the specified comparator.

Read: Reverse Order Comparator in Apache Commons Collections

 
 
References: Comparator (Java Platform SE 8 )

 
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 🙂
 


Get great deals at Amazon




Leave a Reply

Notify of
avatar
wpDiscuz