This post will discuss how to sort a list of objects using Comparator in Java.

A Comparator is a comparison function, which provides an ordering for collections of objects that don’t have a natural ordering. This class’s implementer needs to override the abstract method compare() defined in java.util.Comparator, which compares its two arguments for order. The value returned by the compare() method decides the position of the first object relative to the second object.

  • If compare() returns a negative integer, the first argument is less than the second.
  • If compare() returns a zero, the first argument is equal to the second.
  • If compare() returns a positive integer, the first argument is greater than the second.

 
There are several ways to implement Comparators in Java:

1. Pass Comparator as argument to sort() method

Comparators, if passed to a sort method (such as Collections.sort (and Arrays.sort), allow precise control over the sort order. In the following example, we obtain a Comparator that compares Person objects by their age.

Download  Run Code

Output:

[{name='Joe', age=10}, {name='John', age=15}, {name='Will', age=20}, {name='Dan', age=20}, {name='Sam', age=25}]

 
Since Comparator is a functional interface, it can be used as the assignment target for a lambda expression or method reference. Therefore,

can be rewritten as:

 
Java 8 introduced several enhancements to the Comparator interface. Now Comparator has static methods like comparing(), which can easily create Comparators to compare some specific values from objects. For example, to obtain a Comparator that compares Person objects by their age, we can do:

 
The above code will sort the person’s list only by the age field. If two people have the same age, their relative ordering in the sorted list is not fixed. So, it is preferred to compare objects using multiple fields to avoid such cases.

How to compare objects against the multiple fields?

1. We can easily sort the person’s list first by age and then by name, as shown below. Now for persons having the same age, the ordering is decided by the person’s name.

Download  Run Code

 
Note that we have simply reduced the value of int primitive type age from each other while for the String object, built-in comparison method compareTo() is used. Typically, this chain can continue further to include other properties as well.

 
2. We can also do this with lambda expressions by using the .thenComparing() method, which effectively combines two comparisons into one:

Download  Run Code

 
3. We can also use Guava’s ComparisonChain for performing a chained comparison statement, as shown below:

Download Code

 
The return value of the compare() method will have the same sign as the first nonzero comparison result in the chain or will be zero if every comparison result was zero. Note that the ComparisonChain stops calling its inputs compareTo and compare methods as soon as one of them returns a nonzero result.

 
4. We can also use the CompareToBuilder class of the Apache Commons Lang library to assist in implementing the Comparator.compare() method. To use this class, write code as follows:

Download Code

 
Values are compared in the order they are appended to the builder. If any comparison returns a nonzero result, then that value will be returned by toComparison(), and all subsequent comparisons are skipped.

2. Implement Comparator in a separate class

We can even implement Comparator in a separate class and then pass that class’s instance to the sort() method. This is demonstrated below:

Download  Run Code

Output:

[{name='Joe', age=10}, {name='John', age=15}, {name='Dan', age=20}, {name='Will', age=20}, {name='Sam', age=25}]

3. Pass Comparator to List.sort() method

Java 8 introduced several enhancements to the List interface. Now List has its own sorting method sort() which sorts the list according to the order induced by the specified Comparator. This is demonstrated below:

Download  Run Code

Output:

[{name='Joe', age=10}, {name='John', age=15}, {name='Dan', age=20}, {name='Will', age=20}, {name='Sam', age=25}]

4. Pass Comparator to Stream.sorted() method

We can also pass our comparator to the sorted() method of the Stream class, which returns a stream consisting of the elements of this stream, sorted according to the provided Comparator. Here’s a working example:

Download  Run Code

Output:

[{name='Joe', age=10}, {name='John', age=15}, {name='Dan', age=20}, {name='Will', age=20}, {name='Sam', age=25}]

That’s all about sorting a list of objects using Comparator in Java.

 
Continue reading:

Sort a list of objects using Comparable in Java