Thursday, July 19, 2018

Comparator interface and its example in java

In our previous post we have learn about what is comparable , In this article we will see basics about Comparator.

#What is Comparator ?
Comparator is a interface which is used to order the different user defined objects. When we have 2 object of different classes we want to order them we will use comparator.

Learn about What is Comparable?

#UserCase :
We have an array of person , we want to sort them on different basis , like on the basis of age of the person , or on the basis of name of the person. there are 2 questions comes in our mind , can we use comparable , - No ( as we can only compare on one of the 2 basis not both) , can we use comparator - Yes .


  1. We will first create one person class .
  2. Now we will create 2 different Custom Comparator classes which will implements Comparator<person>
    1. One will be AgeComparator.
    2. Second will be NameComparator.
  3. Now we will create one Main class where we will create list of person. and then we will use Collections.sort and pass the list along with the comparator , we want to use for sorting.

class Person{
 int age;
 String name;
 public int getAge() {
  return age;
 public void setAge(int age) {
  this.age = age;
 public String getName() {
  return name;
 public void setName(String name) { = name;
 public String toString() {
  return "Person [age=" + age + ", name=" + name + "]";

class AgeComparator implements Comparator<Person>{

 public int compare(Person arg0, Person arg1) {
  // TODO Auto-generated method stub
  return arg0.getAge() - arg1.getAge();

class NameComparator implements Comparator<Person>{

 public int compare(Person o1, Person o2) {
  // TODO Auto-generated method stub
  return o1.getName().compareTo(o2.getName());

Main Class

public class ComparatorDemo {
 public static void main(String[] args) {
  List<Person> list = new ArrayList<>();
  Person p1 = new Person();
  Person p2 = new Person();
//  Collections.sort(list,new AgeComparator());
  Collections.sort(list,new NameComparator());
  list.forEach(s-> System.out.println(s));


Person [age=45, name=rohan]
Person [age=35, name=vishal]

Here we can see that the Objects are sorted on the basis of name , we can also do it by using age comparator as well.

If you have any issue , Please let us know , if you want any other topic to be covered in our next article please leave us a comment.

If you like this article please share it with your friends as well.

Thanks for reading


Post a Comment