Comparator in java

In this post, we will see  how you can use comparator to sort list of objects in java.


When you want to sort list of objects of a class.You can use Comparator interface. Class whose objects to be sorted do not need to implement this interface.Some third class can implement this interface to sort.e.g.CountrySortByIdComparator class can implement Comparator interface to sort collection of country object by id. For example:

Using Comparator interface,we can write different sorting based on different attributes of objects to be sorted.You can use anonymous comparator to compare at particular line of code.We will see more about it later. For example:

Java code for Comparator:

We will create class country having attribute id and name and will create another class CountrySortByIdComparator which will implement Comparator interface and implement compare method to sort collection of country object by id.


Anonymous Comparator:

One of advantage of Comparator over comparable is you can create anonymous comparator i.e you don’t need to implement Comparable interface to any class.You just need to pass objects to compare method. Lets understand more with help of example:


So here we have created anonymous Comparator to sort country by name. We have not implemented Comparator to Country class , neither we have created any Comparator specific class.

Add Comment