Comparator example in java

As the name suggest, The Comparator is used for comparing objects in Java. Using this concepts; Java objects can be sorted according to a predefined order

A comparator object is capable of comparing two different objects. The class is not comparing its instances, but some other class’s instances. This comparator class must implement the java.util.Comparator interface.

Why we need to compare the objects?

When there is a list of objects, ordering these objects into different orders becomes a must in some situations. For example; think of displaying a list of Person objects in a web page. Generally person may be displayed by sorting them using the person id. Also there will be requirements to sort them according to the name or age as well. In these situations we need the comparator concepts.

How to use Comparator?

You can use Comparator many ways. Some of the methods are defined here.

Your object which has to be sort based on property of the object should implement the Comparator interface and the compare method should be implemented by you.

java.util.Comparator: int compare(Object obj1, Object obj2)

This method compares obj1 and obj2 objects. Returned int value has the following meanings.

positive – obj1 is greater than obj2

zero – obj1 equals to obj2

negative – obj1 is less than obj2

The java Collections framework utility classes provide the basic method for sorting of objects for natural order.

java.util.Collections.sort(List) and java.util.Arrays.sort(Object[]) methods can be used to sort using natural ordering of objects.

java.util.Collections.sort(List, Comparator) and java.util.Arrays.sort(Object[], Comparator) methods can be used if a Comparator is available for comparison.

The above explained Person example is a good candidate for explaining the Comparator concepts. First we will write a simple Java bean to represent the Comparator.

The below code show the Person object implementation.

class Person {
 
    private int personId;
    private String name;
    private int age;
 
    public Person(int personId, String name, int age) {
        super();
        this.personId = personId;
        this.name = name;
        this.age = age;
    }
 
    public int getPersonId() {
        return personId;
    }
 
    public void setPersonId(int personId) {
        this.personId = personId;
    }
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    public int getAge() {
        return age;
    }
 
    public void setAge(int age) {
        this.age = age;
    }
}

Now we will create the list of person object without any specific order like below code snap.

   public static List<person> getPersons() {
        List<person> list = new ArrayList<person>();
        list.add(new Person(1, "Shekar", 21));
        list.add(new Person(2, "Akshay", 20));
        list.add(new Person(3, "Manish", 22));
        list.add(new Person(4, "Dinesh", 26));
        list.add(new Person(5, "Alex", 28));
        list.add(new Person(6, "Ramlal", 32));
        list.add(new Person(7, "Murli", 40));
        list.add(new Person(8, "Rakesh", 33));
        return list;
    }

Next, you can see the PersonSortByName class it implements the Comparator interface and override the compare method and using the name attributes in order to sort.

class PersonSortByName implements Comparator<person> {
    // Override the compare method of Comparator
    public int compare(Person obj1, Person obj2) {
        return obj1.getName().compareTo(obj2.getName());
    }
}

Now you can use PersonSortByName Comparator to sort the list based on person name.

public static void main(String[] args) {
        List<person> list = getPersons();
        Collections.sort(list, new PersonSortByName());
 
    }

And the output of the above code will be as:

PersonId    Name    Age
2       Akshay  20
5       Alex    28
4       Dinesh  26
3       Manish  22
7       Murli   40
8       Rakesh  33
6       Ramlal  32
1       Shekar  21