Difference between Comparable and Comparator

Comparable and Comparator both are interfaces and can be used to sort collection elements.

However, there are many differences between Comparable and Comparator interfaces that are given below.

Comparable Comparator
1) Comparable provides aย single sorting sequence. In other words, we can sort the collection on the basis of a single element such as id, name, and price. The Comparator providesย multiple sorting sequences. In other words, we can sort the collection on the basis of multiple elements such as id, name, and price etc.
2) Comparableย affects the original class, i.e., the actual class is modified. Comparatorย doesn’t affect the original class, i.e., the actual class is not modified.
3) Comparable providesย compareTo() methodย to sort elements. Comparator providesย compare() methodย to sort elements.
4) Comparable is present inย java.langย package. A Comparator is present in theย java.utilย package.
5) We can sort the list elements of Comparable type byย Collections.sort(List)ย method. We can sort the list elements of Comparator type byย Collections.sort(List, Comparator)ย method.

 

Java providesย Comparableย interface which should be implemented by any custom class if we want to use Arrays or Collections sorting methods. The Comparable interface hasย compareTo(T obj)ย method which is used by sorting methods, you can check any Wrapper, String or Date class to confirm this. We should override this method in such a way that it returns a negative integer, zero, or a positive integer if โ€œthisโ€ object is less than, equal to, or greater than the object passed as an argument.

After implementing Comparableย interfaceย in Employee class, here is the resulting Employee class.


package com.techgyani.sort;

import java.util.Comparator;

public class Employee implements Comparable<Employee> {

    private int id;
    private String name;
    private int age;
    private long salary;

    public int getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    public long getSalary() {
        return salary;
    }

    public Employee(int id, String name, int age, int salary) {
        this.id = id;
        this.name = name;
        this.age = age;
        this.salary = salary;
    }

    @Override
    public int compareTo(Employee emp) {
        //let's sort the employee based on an id in ascending order
        //returns a negative integer, zero, or a positive integer as this employee id
        //is less than, equal to, or greater than the specified object.
        return (this.id - emp.id);
    }

    @Override
    //this is required to print the user-friendly information about the Employee
    public String toString() {
        return "[id=" + this.id + ", name=" + this.name + ", age=" + this.age + ", salary=" +
                this.salary + "]";
    }

}

Now when we execute the above snippet for Arrays sorting of Employees and print it, here is the output.


Default Sorting of Employees list:
[[id=1, name=Pankaj, age=32, salary=50000], [id=5, name=Lisa, age=35, salary=5000], [id=10, name=Mikey, age=25, salary=10000], [id=20, name=Arun, age=29, salary=20000]]

As you can see that Employees array is sorted by id in ascending order.

But, in most real-life scenarios, we want sorting based on different parameters. For example, as a CEO, I would like to sort the employees based on Salary, an HR would like to sort them based on the age. This is the situation where we need to useย Java Comparatorย interface becauseย Comparable.compareTo(Object o)method implementation can provide default sorting and we canโ€™t change it dynamically. Whereas with Comparator, we can define multiple methods with different ways of sorting and then chose the sorting method based on our requirements.

Java Comparator

Comparator interfaceย compare(Object o1, Object o2)ย method need to be implemented that takes two Object argument, it should be implemented in such a way that it returns negative int if the first argument is less than the second one and returns zero if they are equal and positive int if the first argument is greater than the second one.

Comparable and Comparator interfaces useย Genericsย for compile-time type checking, learn more aboutย Java Generics.

Here is how we can create different Comparator implementation in the Employee class.


/**
     * Comparator to sort employees list or array in order of Salary
     */
    public static Comparator<Employee> SalaryComparator = new Comparator<Employee>() {

        @Override
        public int compare(Employee e1, Employee e2) {
            return (int) (e1.getSalary() - e2.getSalary());
        }
    };

    /**
     * Comparator to sort employees list or array in order of Age
     */
    public static Comparator<Employee> AgeComparator = new Comparator<Employee>() {

        @Override
        public int compare(Employee e1, Employee e2) {
            return e1.getAge() - e2.getAge();
        }
    };

    /**
     * Comparator to sort employees list or array in order of Name
     */
    public static Comparator<Employee> NameComparator = new Comparator<Employee>() {

        @Override
        public int compare(Employee e1, Employee e2) {
            return e1.getName().compareTo(e2.getName());
        }
    };

All the above implementations of Comparator interface areย anonymous classes.

We can use these comparators to pass an argument to sort function of Arrays and Collections classes.


//sort employees array using Comparator by Salary
Arrays.sort(empArr, Employee.SalaryComparator);
System.out.println("Employees list sorted by Salary:\n"+Arrays.toString(empArr));

//sort employees array using Comparator by Age
Arrays.sort(empArr, Employee.AgeComparator);
System.out.println("Employees list sorted by Age:\n"+Arrays.toString(empArr));

//sort employees array using Comparator by Name
Arrays.sort(empArr, Employee.NameComparator);
System.out.println("Employees list sorted by Name:\n"+Arrays.toString(empArr));

Here is the output of the above code snippet:


Employees list sorted by Salary:
[[id=5, name=Lisa, age=35, salary=5000], [id=10, name=Mikey, age=25, salary=10000], [id=20, name=Arun, age=29, salary=20000], [id=1, name=Pankaj, age=32, salary=50000]]
Employees list sorted by Age:
[[id=10, name=Mikey, age=25, salary=10000], [id=20, name=Arun, age=29, salary=20000], [id=1, name=Pankaj, age=32, salary=50000], [id=5, name=Lisa, age=35, salary=5000]]
Employees list sorted by Name:
[[id=20, name=Arun, age=29, salary=20000], [id=5, name=Lisa, age=35, salary=5000], [id=10, name=Mikey, age=25, salary=10000], [id=1, name=Pankaj, age=32, salary=50000]]

So now we know that if we want to sort java object array or list, we need to implement java Comparable interface to provide default sorting and we should implement java Comparator interface to provide different ways of sorting.

We can also create separate class that implementsย Comparatorย interface and then use it.

Here is the final classes we have explainingย Comparable and Comparatorย in Java.


package com.techgyani.sort;

import java.util.Comparator;

public class Employee implements Comparable<Employee> {

    private int id;
    private String name;
    private int age;
    private long salary;

    public int getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    public long getSalary() {
        return salary;
    }

    public Employee(int id, String name, int age, int salary) {
        this.id = id;
        this.name = name;
        this.age = age;
        this.salary = salary;
    }

    @Override
    public int compareTo(Employee emp) {
        //let's sort the employee based on an id in ascending order
        //returns a negative integer, zero, or a positive integer as this employee id
        //is less than, equal to, or greater than the specified object.
        return (this.id - emp.id);
    }

    @Override
    //this is required to print the user-friendly information about the Employee
    public String toString() {
        return "[id=" + this.id + ", name=" + this.name + ", age=" + this.age + ", salary=" +
                this.salary + "]";
    }

    /**
     * Comparator to sort employees list or array in order of Salary
     */
    public static Comparator<Employee> SalaryComparator = new Comparator<Employee>() {

        @Override
        public int compare(Employee e1, Employee e2) {
            return (int) (e1.getSalary() - e2.getSalary());
        }
    };

    /**
     * Comparator to sort employees list or array in order of Age
     */
    public static Comparator<Employee> AgeComparator = new Comparator<Employee>() {

        @Override
        public int compare(Employee e1, Employee e2) {
            return e1.getAge() - e2.getAge();
        }
    };

    /**
     * Comparator to sort employees list or array in order of Name
     */
    public static Comparator<Employee> NameComparator = new Comparator<Employee>() {

        @Override
        public int compare(Employee e1, Employee e2) {
            return e1.getName().compareTo(e2.getName());
        }
    };
}

Here is the separate class implementation of Comparator interface that will compare two Employees object first on their id and if they are same then on the name.


package com.techgyani.sort;

import java.util.Comparator;

public class EmployeeComparatorByIdAndName implements Comparator<Employee> {

    @Override
    public int compare(Employee o1, Employee o2) {
        int flag = o1.getId() - o2.getId();
        if(flag==0) flag = o1.getName().compareTo(o2.getName());
        return flag;
    }

}

Here is the test class where we are using different ways to sort Objects in java using Comparable and Comparator.


package com.techgyani.sort; import java.util.Arrays; public class JavaObjectSorting { /** * This class shows how to sort custom objects array/list * implementing Comparable and Comparator interfaces * @param args */ public static void main(String[] args) { //sorting custom object array Employee[] empArr = new Employee[4]; empArr[0] = new Employee(10, "Mikey", 25, 10000); empArr[1] = new Employee(20, "Arun", 29, 20000); empArr[2] = new Employee(5, "Lisa", 35, 5000); empArr[3] = new Employee(1, "Pankaj", 32, 50000); //sorting employees array using Comparable interface implementation Arrays.sort(empArr); System.out.println("Default Sorting of Employees list:\n"+Arrays.toString(empArr)); //sort employees array using Comparator by Salary Arrays.sort(empArr, Employee.SalaryComparator); System.out.println("Employees list sorted by Salary:\n"+Arrays.toString(empArr)); //sort employees array using Comparator by Age Arrays.sort(empArr, Employee.AgeComparator); System.out.println("Employees list sorted by Age:\n"+Arrays.toString(empArr)); //sort employees array using Comparator by Name Arrays.sort(empArr, Employee.NameComparator); System.out.println("Employees list sorted by Name:\n"+Arrays.toString(empArr)); //Employees list sorted by ID and then name using Comparator class empArr[0] = new Employee(1, "Mikey", 25, 10000); Arrays.sort(empArr, new EmployeeComparatorByIdAndName()); System.out.println("Employees list sorted by ID and Name:\n"+Arrays.toString(empArr)); } } 

Here is the output of the above program:


Default Sorting of Employees list:
[[id=1, name=Pankaj, age=32, salary=50000], [id=5, name=Lisa, age=35, salary=5000], [id=10, name=Mikey, age=25, salary=10000], [id=20, name=Arun, age=29, salary=20000]]
Employees list sorted by Salary:
[[id=5, name=Lisa, age=35, salary=5000], [id=10, name=Mikey, age=25, salary=10000], [id=20, name=Arun, age=29, salary=20000], [id=1, name=Pankaj, age=32, salary=50000]]
Employees list sorted by Age:
[[id=10, name=Mikey, age=25, salary=10000], [id=20, name=Arun, age=29, salary=20000], [id=1, name=Pankaj, age=32, salary=50000], [id=5, name=Lisa, age=35, salary=5000]]
Employees list sorted by Name:
[[id=20, name=Arun, age=29, salary=20000], [id=5, name=Lisa, age=35, salary=5000], [id=10, name=Mikey, age=25, salary=10000], [id=1, name=Pankaj, age=32, salary=50000]]
Employees list sorted by ID and Name:
[[id=1, name=Mikey, age=25, salary=10000], [id=1, name=Pankaj, age=32, salary=50000], [id=5, name=Lisa, age=35, salary=5000], [id=10, name=Mikey, age=25, salary=10000]]

Theย java.lang.Comparableย andย java.util.Comparatorย are powerful interfaces that can be used to provide sorting objects in java.

Newsletter Updates

Enter your name and email address below to subscribe to our newsletter

One comment

  1. […] can useย Comparator interfaceย to sort, It only contain one abstract method: โ€“ […]

Leave a Reply