Sort an arraylist using comparator and comparable interface

One of the most popular technical interview questions, is that you have an arraylist holding multiple custom Employee class objects, then how can you sort this arraylist on the basis of employee name? Using Comparator or Comparable interfaces is an answer to it. If the arraylist had contained String or any of the primitive wrapper class objects, like Integer, Short, Double and so on, the sorting would have been lot easier. You just need to call the method:

and you are done.

Check out the below snippet for the same.

The same applies for a list of String or any of the primitive wrapper class objects. That is the reason I emphasized on the word ‘custom’ in the first line of this tutorial.

Now suppose, I have an Employee class as:

Now, I want the sorting to be done, based on the employee age.


Using comparable:

Implement Comparable to Employee class and then over-ride the compareTo method as:

Now, you need to call the same Collections.sort() method as:

Using Comparator:

Implement the same Employee class this time with Comparator and over-ride the compare method as:

Now, you need to call the same Collections.sort() method as:

Why do we need Comparator, when Comparable is already there?

Using Comparable we can sort only on the basis of single property. In order to sort an ArrayList based on multiple properties we need Comparator.

Let us see, how can we use Comparator to sort an arraylist based on multiple properties. Consider a scenario, where I want the employees to be arranged on the basis of their empId, empName and empAge, in the same order. That means if the empName is same for two employees, they will be re-arranged on the basis of their age.

All you need to do, modify the above compare method as:

Receive our updates to your inbox

Get more stuff like this
in your inbox

Subscribe to our mailing list and get interesting stuff and updates to your email inbox.