Pages

In this tutorial, we will see Java Comparator example to sort an Employee object by name, age and salary. In order to sort Employee object on different criterion, we need to create multiple comparators e.g. NameComparator, AgeComparator and SalaryComparator, this is known as custom sorting in Java. This is different then natural ordering of object, provided by compareTo() method of java.lang.Comparable interface. Though both compare() and compareTo() method looks similar they are different in a sense that, former accept one parameter, while later accept two parameter. Former compare passed object to current object, on the other hand compare() method compares two different object passed to it.
You can create this comparator as nested static class, because they require access of private members of class.

Once you create these Comparator implementations, all you need to do is to override compare() method accordingly e.g. in compare() method of NameComparator compare name of two employee and return positive if name of first employee is greater than second, and return negative if name of first employee is less than second and return zero if name of both employees are equal.

By using Generics, you can avoid casting of object into Employee inside compare() method, as shown in example of this article. Once you have your Comparator classes ready, you can create a bunch of employee and sort them using any Comparator by passing List of employees and Comparator into Collections.sort(List, Comparator) method.

By the way this Java example also implements equals(), hashcode(), compareTo() and toString() method for Employee object, along with JUnit test for testing various Comparator implementation in file EmployeeTest.java.

Custom Sorting in Java using Comparator Example

Here is complete code of creating different Comparator classes to compare objects on different attributes. In our example we have an Employee object, which has fields like int id, String name, int salary, int age and Date field to represent date of joining. Our requirement is to sort a List of employee based upon their name, age, salary and date of joining. For this purpose we have created four different comparator classes namely NameComparator, AgeComparator, SalaryComparator and DOJComparator. All classes implements java.util.Comparator interface but their compare() method are overridden differently e.g. first one compares name of two employee object, second compares their salary, third compare their age and last one compare their age. When overriding compare() method, if you find an object, which overrides compareTo() then invoke that, for example for comparing String and Date we are invoking their compareTo() methods.

Files to run this Example
Employee.java
EmployeeTest.java

In order to run this program, simply copy paste following two classes in two different Java source file. Then name them according to name of public class e.g. Employee.java and EmployeeTest.java. You also need JUnit to run test file, which test the code you have written for implementing Comparator and overriding compare() method. You can run it on Eclipse or command prompt as per your convenience. If you are not using JUnit then you just put the test code inside main method of any class and run it accordingly.

That's all on this Java Comparator example tutorial. We have learned how to create multiple Comparator in a class for comparing object in different parameters. This allows you to sort object in any custom order, depending upon business requirement. You can provide custom Comparator as nested static class, because a Comparator is closely associated with the object it compare. This is one of the genuine usage of nested static class in Java. It's good to provide natural ordering of object via compareTo() method and provide additional compare() methods for custom sorting of object in Java. Always use Generics while overriding compare(), this will make your program as now your compare() will accept two Employee object, instead of two java.lang.Object parameters.

A small correction - Instead of "Though both compare() and compareTo() method looks similar they are different in a sense that, FORMER accept one parameter, while LATER accept two parameter.", it should be former (compare())accept two parameters and later(compareTo()) accepts one parameter

From Java 8 onwards you can use lambda expression instead of anonymous class to implement custom comparator. You can also use method reference and some useful methods like Comparator::comparing() to sort with multiple attributes.

For example, your code for sorting employees based upon salary can be re-written in Java 8 as follows :

Collections.sort(employees, Comparator.comparing(Employee::salary));

This will sort all employees on increasing order of salary, but if you want to sort in decreasing order, you can just do this :

Nice article, but there are some mistakes in example. Syntax of compare() and compareTo() are not correct. For Example, Instead of public int compare(Employee o1, Employee o2) , It should be public int compare(Object o1, Object o2)Please correct the example.Instead of

@Chandra, look at closely mate, we are using Anonymous class, which means a class which implements Comparator interface and that's why we are able to create instance using new() keyword. The logic of implementation is always in the overridden compare() method.

Hello Javin. Recently i was asked in interview. Suppose i have a list of heterogeneous objects e.g. Student,employee,person,etc. Each having a common property firstName, how to write a comparator for it and it should not do any instanceOf checking.

Hello friends, I was asked a question in an interview regarding comparator interface, they ask me how to sort employee id & employee name using only one comparator class. you can't create two separate comparator class for id comparator & name comparator.Sorting must be customized sorting order. Please one body answer me.

@Anonymous, when you call the sort method, you give a list of employee and a Comparator to compare them. The Java uses a modified version of Mergesort to sort the list of employee and for comparing two employee it uses the Comparator you have provided.

Hello @Kanhu, are they after a Comparator which first sort on ID and then on NAME? e.g. if two employee have same id then check their name? if yes then it's possible, you can do that in compare() method, just check if id is equal first if they are then check if name is equal then return 0 or 1 or -1 accordingly e.g.