Java Comparator interface example

Java Comparator interface used to sort a array or list of objects based on custom order. Custom ordering of elements is imposed by implementing Comparator.compare() method in the objects.

1. Java Comparator interface

Java Comparator interface imposes a total ordering on the objects which may not have a natural ordering.

For example, for a list of elpmoyees object, the natural order may be order by employee id. But in real life applications, we may want to sort the list of employees by their first name, date of birth or simply any other such criteria. In such conditions, we need to use Comparator interface.

We can use Comparator interface in following situations.

  1. Sort the array or list of objects, but NOT in natural order.
  2. Sort the array or list of objects where we can not modify the object’s source code to implement Comparable interface.
  3. Sort same list or array of objects on different fields.
  4. Using group by sort on list or array of objects on different fields.

1.1. Comparator.compare()

To enable total ordering on objects, we need to create class which implements Comparator interface. Then we need to override it’s compare(T o1, T o2) method.

It compares its two arguments for order. It returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.

The implementor must also ensure that the relation is transitive: ((compare(x, y)>0) && (compare(y, z)>0)) implies compare(x, z)>0.

import java.time.LocalDate;

public class Employee implements Serializable {

    private static final long serialVersionUID = 1L;

    private Long id;
    private String name;
    private LocalDate dob;

    //Getters and Setters

    @Override
    public String toString() {
        return "Employee [id=" + id + ", name=" + name + ", dob=" + dob + "]";
    }
}

For above class, an order by employee name can be imposed by creating Comparator like below.

import java.util.Comparator;

public class NameSorter implements Comparator<Employee>
{
    @Override
    public int compare(Employee e1, Employee e2) {
        return e1.getName().compareToIgnoreCase( e2.getName() );
    }
}

1.2. Collections.sort() and Arrays.sort()

  1. Use Collections.sort(list, Comparator) method sort a list of objects in order imposed by provided comparator instance.
  2. Use Arrays.sort(array, Comparator) method sort an array of objects in order imposed by provided comparator instance.

1.3. Collections.comparing()

This utility method accepts a function that extracts a sort key for the class. This is essentially a field on which the class objects will be sorted.

//Order by name
Comparator.comparing(Employee::getName);

//Order by name in reverse order
Comparator.comparing(Employee::getName).reversed();

//Order by id field
Comparator.comparing(Employee::getId);

//Order by employee age
Comparator.comparing(Employee::getDate);

1.4. Collections.thenComparing()

This utility method is used for group by sort. Using this method, we can chain multiple comparators to sort the list or array of objects on multiple fields.

It is very similar to SQL GROUP BY clause to order rows on different fields.

//Order by name and then by age
Comparator.comparing(Employee::getName)
			.thenComparing(Employee::getDob);

//Order by name -> date of birth -> id 
Comparator.comparing(Employee::getName)
			.thenComparing(Employee::getDob)
			.thenComparing(Employee::getId);

Using above syntax, we can create virtually any sorting logic.

1.5. Collections.reverseOrder()

This utility method returns a comparator that imposes the reverse of the natural ordering or total ordering on a collection of objects that implement the Comparable interface.

//Reverse of natural order as specified in 
//Comparable interface's compareTo() method 

Comparator.reversed();

//Reverse of order by name

Comparator.comparing(Employee::getName).reversed();

2. Java Comparator example

2.1. Sort list of objects

Java example to sort a list of employees by name using Comparator.

ArrayList<Employee> list = new ArrayList<>();
        
list.add(new Employee(22l, "Lokesh", LocalDate.now()));
list.add(new Employee(30l, "Bob", LocalDate.now()));
list.add(new Employee(18l, "Alex", LocalDate.now()));
list.add(new Employee(5l, "David", LocalDate.now()));
list.add(new Employee(600l, "Charles", LocalDate.now()));

//Sort in reverse natural order
Collections.sort(list, new NameSorter());

System.out.println(list);

Program Output.

[
	Employee [id=18, name=Alex, dob=2018-10-30], 
	Employee [id=30, name=Bob, dob=2018-10-30], 
	Employee [id=600, name=Charles, dob=2018-10-30], 
	Employee [id=5, name=David, dob=2018-10-30], 
	Employee [id=22, name=Lokesh, dob=2018-10-30]
]

2.2. Sort list of objects in reverse order

Java example to sort a list of employees by name using Comparator in reverse order.

ArrayList<Employee> list = new ArrayList<>();
        
list.add(new Employee(22l, "Lokesh", LocalDate.now()));
list.add(new Employee(30l, "Bob", LocalDate.now()));
list.add(new Employee(18l, "Alex", LocalDate.now()));
list.add(new Employee(5l, "David", LocalDate.now()));
list.add(new Employee(600l, "Charles", LocalDate.now()));

Collections.sort(list, Comparator.comparing( Employee::getName ).reversed());

System.out.println(list);

Program Output.

[
	Employee [id=22, name=Lokesh, dob=2018-10-30], 
	Employee [id=5, name=David, dob=2018-10-30], 
	Employee [id=600, name=Charles, dob=2018-10-30], 
	Employee [id=30, name=Bob, dob=2018-10-30], 
	Employee [id=18, name=Alex, dob=2018-10-30]
]

2.3. Group by sorting list of objects in multiple fields

Java example to sort a list of employees on multiple fields i.e. field by field.

ArrayList<Employee> list = new ArrayList<>();
        
list.add(new Employee(22l, "Lokesh", LocalDate.now()));
list.add(new Employee(30l, "Lokesh", LocalDate.now()));
list.add(new Employee(18l, "Alex", LocalDate.now()));
list.add(new Employee(5l, "Lokesh", LocalDate.now()));
list.add(new Employee(600l, "Charles", LocalDate.now()));

Comparator<Employee> groupByComparator = Comparator.comparing(Employee::getName)
                                        .thenComparing(Employee::getDob)
                                        .thenComparing(Employee::getId);

Collections.sort(list, groupByComparator);

System.out.println(list);

Program Output.

[
	Employee [id=18, name=Alex, dob=2018-10-30], 
	Employee [id=600, name=Charles, dob=2018-10-30], 
	Employee [id=5, name=Lokesh, dob=2018-10-30], 
	Employee [id=22, name=Lokesh, dob=2018-10-30], 
	Employee [id=30, name=Lokesh, dob=2018-10-30]]

3. Conclusion

In this tutorial, we learned about Comparator interface of Java collection framework. It helps in imposing a total order on objects without any change to sourcecode of that class.

We learned to sort list and array of objects. We learned how to sort employee objects in java using Comparator interface i.e. java comparator example multiple fields.

Drop me your questions in comments section.

Happy Learning !!

References:

Comparator Interface Java Docs

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.