Tutorial

Comparable and Comparator in Java Example

Published on August 3, 2022
author

Pankaj

Comparable and Comparator in Java Example

Comparable and Comparator in Java are very useful for sorting the collection of objects. Java provides some inbuilt methods to sort primitive types array or Wrapper classes array or list. Here we will first learn how we can sort an array/list of primitive types and wrapper classes and then we will use java.lang.Comparable and java.util.Comparator interfaces to sort array/list of custom classes. Let’s see how we can sort primitive types or Object array and list with a simple program.

package com.journaldev.sort;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class JavaObjectSorting {

    /**
     * This class shows how to sort primitive arrays, 
     * Wrapper classes Object Arrays
     * @param args
     */
    public static void main(String[] args) {
        //sort primitives array like int array
        int[] intArr = {5,9,1,10};
        Arrays.sort(intArr);
        System.out.println(Arrays.toString(intArr));
        
        //sorting String array
        String[] strArr = {"A", "C", "B", "Z", "E"};
        Arrays.sort(strArr);
        System.out.println(Arrays.toString(strArr));
        
        //sorting list of objects of Wrapper classes
        List<String> strList = new ArrayList<String>();
        strList.add("A");
        strList.add("C");
        strList.add("B");
        strList.add("Z");
        strList.add("E");
        Collections.sort(strList);
        for(String str: strList) System.out.print(" "+str);
    }
}

Output of the above program is:

[1, 5, 9, 10]
[A, B, C, E, Z]
 A B C E Z

Now let’s try to sort an array of objects.

package com.journaldev.sort;

public class 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
    //this is overridden 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 + "]";
    }

}

Here is the code I used to sort the array of Employee objects.

//sorting 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));

When I tried to run this, it throws the following runtime exception.

Exception in thread "main" java.lang.ClassCastException: com.journaldev.sort.Employee cannot be cast to java.lang.Comparable
	at java.util.ComparableTimSort.countRunAndMakeAscending(ComparableTimSort.java:290)
	at java.util.ComparableTimSort.sort(ComparableTimSort.java:157)
	at java.util.ComparableTimSort.sort(ComparableTimSort.java:146)
	at java.util.Arrays.sort(Arrays.java:472)
	at com.journaldev.sort.JavaSorting.main(JavaSorting.java:41)

Comparable and Comparator

comparable and comparator, comparable vs comparator, comparable and comparator in java 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.journaldev.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 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.journaldev.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.journaldev.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.journaldev.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.

Comparable vs Comparator

  1. Comparable interface can be used to provide single way of sorting whereas Comparator interface is used to provide different ways of sorting.
  2. For using Comparable, Class needs to implement it whereas for using Comparator we don’t need to make any change in the class.
  3. Comparable interface is in java.lang package whereas Comparator interface is present in java.util package.
  4. We don’t need to make any code changes at client side for using Comparable, Arrays.sort() or Collection.sort() methods automatically uses the compareTo() method of the class. For Comparator, client needs to provide the Comparator class to use in compare() method.

Do you know that Collections.sort() method that takes Comparator argument follows Strategy Pattern?

You can checkout complete code and more core java examples from our GitHub Repository.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the author(s)

Category:
Tutorial
Tags:

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
February 6, 2013

very nicely written.

- Roshan

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    May 20, 2013

    private int id; private String name; private int age; private long salar y; Kids kids; like kids i have reference in kids class also i have 2 parameters age,nofkids like i need sorting salary accending and kids age desending please any one can clarify…

    - Nagesh kaniganti

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      August 10, 2013

      Hi, nice explanation with the programs…but you didn’t print the strArray in the second Sysout statement at the first program. you can change it from intArr to strArr. Thanks …

      - Muralidhar N

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      August 10, 2013

      yeah right, changed the program. Thanks for spotting it.

      - Pankaj

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        September 24, 2013

        This must be an easy question for you guys. But can you please provide me the explanation of the following statetment. “return e1.getName().compareTo(e2.getName())”. Below are my specific queries: 1. Do we need to override comapreTo method even if we are implementing Comaparator and want to sort on the bases of name. 2. In the above mentioned example you have provided definition to comapreTo() in which you are sorting on the basis of ID. But then while sorting according to name you are still calling the comapreTo() method. Please explain as it is very confusing. Thanks

        - Sandy

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        September 24, 2013

        Hi Sandy, 1. Employee.NameComparator is an anonymous inner class, the example is given to showcase both Comparable and Comparator interfaces, you can use any of these based on your requirements. Read more about inner classes at https://www.journaldev.com/996/java-nested-classes-java-inner-class-static-nested-class-local-inner-class-and-anonymous-inner-class 2. e1.getName().compareTo(e2.getName()) is simply using String class compareTo() method, it’s something like “abc”.compareTo(“123”), it’s not using Employee class compareTo() method. I hope it will clear your confusion.

        - Pankaj

          JournalDev
          DigitalOcean Employee
          DigitalOcean Employee badge
          November 8, 2013

          class A9 { String name,state; java.util.Date date; int age; A9(String name,java.util.Date date,int age) { this.name=name; this.date=date; this.age=age; My question is that how to sort the date using comparator and what should be the format of date,

          - kamaljit

          JournalDev
          DigitalOcean Employee
          DigitalOcean Employee badge
          November 11, 2013

          You can write a comparator for sorting based on date like my example. For sorting dates, you can get the timestamp that is a long value and then compare it.

          - Pankaj

            JournalDev
            DigitalOcean Employee
            DigitalOcean Employee badge
            November 13, 2013

            How to sort String objects in arraylist using compartor and comparable?

            - Raj

            JournalDev
            DigitalOcean Employee
            DigitalOcean Employee badge
            November 15, 2013

            You will have to use the String sorting options.

            - Pankaj

              JournalDev
              DigitalOcean Employee
              DigitalOcean Employee badge
              February 9, 2014

              cleared concept…Amazing work SiR thnxx :)

              - prateek

                JournalDev
                DigitalOcean Employee
                DigitalOcean Employee badge
                February 23, 2014

                Sir,your concept is pure real to focus in an core and deep point of view.We got lot of depth concept by through it thanks.

                - Manash Ranjan Dakua

                JournalDev
                DigitalOcean Employee
                DigitalOcean Employee badge
                May 1, 2014

                superb!!!

                - suraj

                  JournalDev
                  DigitalOcean Employee
                  DigitalOcean Employee badge
                  May 1, 2014

                  write a comparator class to define customized sorting which is alphabetical order of employee name if two employee having same name consider descending order of there age.

                  - Yogesh Pal

                    JournalDev
                    DigitalOcean Employee
                    DigitalOcean Employee badge
                    May 9, 2014

                    Supurb!!! I clearly understand custom objects sorting by this article

                    - indu

                      JournalDev
                      DigitalOcean Employee
                      DigitalOcean Employee badge
                      May 9, 2014

                      good nice article

                      - indu

                        JournalDev
                        DigitalOcean Employee
                        DigitalOcean Employee badge
                        June 17, 2014

                        Best explanation ever. . Thanks :)

                        - Andy

                          JournalDev
                          DigitalOcean Employee
                          DigitalOcean Employee badge
                          June 21, 2014

                          Perfect Explanation .Really it makes me to understand easily

                          - triggergirl

                            JournalDev
                            DigitalOcean Employee
                            DigitalOcean Employee badge
                            July 8, 2014

                            nice explanations

                            - satya

                              JournalDev
                              DigitalOcean Employee
                              DigitalOcean Employee badge
                              July 19, 2014

                              Excellent! Examples My doubt is cleared now…Clearly I tried …tried…but i got it now…Thank u

                              - Niranjan

                                JournalDev
                                DigitalOcean Employee
                                DigitalOcean Employee badge
                                August 27, 2014

                                I have a query. How would i sort the database record after fetching the data from database using Servlet and Jsp. I want to make a column header as a link. On click of column header the all data of the table will be sorted in the basis of that column. I want to do this sorting using coparator interface.

                                - Niraj kumar singh

                                JournalDev
                                DigitalOcean Employee
                                DigitalOcean Employee badge
                                August 27, 2014

                                Check for some javascript functions because you are looking for dynamic sorting on the page itself. I am sure you don’t need any server side communication for this.

                                - Pankaj

                                  JournalDev
                                  DigitalOcean Employee
                                  DigitalOcean Employee badge
                                  August 27, 2014

                                  realty nice explanation as well as very well explanation with example…great !!!

                                  - Atmprakash Sharma

                                    JournalDev
                                    DigitalOcean Employee
                                    DigitalOcean Employee badge
                                    September 10, 2014

                                    Write a program to sort the java objects in the ascending order using SET and only sort by name. public class Test{ private String id; private String name; //Set and Get methods }

                                    - madan

                                      JournalDev
                                      DigitalOcean Employee
                                      DigitalOcean Employee badge
                                      October 5, 2014

                                      Excellent Explanation

                                      - Sridhar

                                        JournalDev
                                        DigitalOcean Employee
                                        DigitalOcean Employee badge
                                        October 29, 2014

                                        Nice Explanation. But i have a doubt in this. In ur blog it says tat “In a Comparable implementation can sort based on one field only and we can’t chose the field on which we want to sort the Object.” But in this case, @Override public int compareTo(Employee emp) { int flag = this.getId() - emp.getId(); if(flag==0) flag = this.getName().compareTo(emp.getName()); return flag; } am using Comparable am overriding compareTo() to sort Employee based on both name and id. Can u explain me your context further.

                                        - Raghav

                                        JournalDev
                                        DigitalOcean Employee
                                        DigitalOcean Employee badge
                                        October 29, 2014

                                        Here we means the client application. In your code above" if client wants to sort based on employee name, its not possible. This is where Comparator is useful.

                                        - Pankaj

                                          JournalDev
                                          DigitalOcean Employee
                                          DigitalOcean Employee badge
                                          May 9, 2014

                                          good nice article

                                          - indu

                                            JournalDev
                                            DigitalOcean Employee
                                            DigitalOcean Employee badge
                                            June 17, 2014

                                            Best explanation ever. . Thanks :)

                                            - Andy

                                              JournalDev
                                              DigitalOcean Employee
                                              DigitalOcean Employee badge
                                              June 21, 2014

                                              Perfect Explanation .Really it makes me to understand easily

                                              - triggergirl

                                                JournalDev
                                                DigitalOcean Employee
                                                DigitalOcean Employee badge
                                                July 8, 2014

                                                nice explanations

                                                - satya

                                                  JournalDev
                                                  DigitalOcean Employee
                                                  DigitalOcean Employee badge
                                                  July 19, 2014

                                                  Excellent! Examples My doubt is cleared now…Clearly I tried …tried…but i got it now…Thank u

                                                  - Niranjan

                                                    JournalDev
                                                    DigitalOcean Employee
                                                    DigitalOcean Employee badge
                                                    August 27, 2014

                                                    I have a query. How would i sort the database record after fetching the data from database using Servlet and Jsp. I want to make a column header as a link. On click of column header the all data of the table will be sorted in the basis of that column. I want to do this sorting using coparator interface.

                                                    - Niraj kumar singh

                                                    JournalDev
                                                    DigitalOcean Employee
                                                    DigitalOcean Employee badge
                                                    August 27, 2014

                                                    Check for some javascript functions because you are looking for dynamic sorting on the page itself. I am sure you don’t need any server side communication for this.

                                                    - Pankaj

                                                      JournalDev
                                                      DigitalOcean Employee
                                                      DigitalOcean Employee badge
                                                      August 27, 2014

                                                      realty nice explanation as well as very well explanation with example…great !!!

                                                      - Atmprakash Sharma

                                                        JournalDev
                                                        DigitalOcean Employee
                                                        DigitalOcean Employee badge
                                                        September 10, 2014

                                                        Write a program to sort the java objects in the ascending order using SET and only sort by name. public class Test{ private String id; private String name; //Set and Get methods }

                                                        - madan

                                                          JournalDev
                                                          DigitalOcean Employee
                                                          DigitalOcean Employee badge
                                                          October 5, 2014

                                                          Excellent Explanation

                                                          - Sridhar

                                                            JournalDev
                                                            DigitalOcean Employee
                                                            DigitalOcean Employee badge
                                                            October 29, 2014

                                                            Nice Explanation. But i have a doubt in this. In ur blog it says tat “In a Comparable implementation can sort based on one field only and we can’t chose the field on which we want to sort the Object.” But in this case, @Override public int compareTo(Employee emp) { int flag = this.getId() - emp.getId(); if(flag==0) flag = this.getName().compareTo(emp.getName()); return flag; } am using Comparable am overriding compareTo() to sort Employee based on both name and id. Can u explain me your context further.

                                                            - Raghav

                                                            JournalDev
                                                            DigitalOcean Employee
                                                            DigitalOcean Employee badge
                                                            October 29, 2014

                                                            Here we means the client application. In your code above" if client wants to sort based on employee name, its not possible. This is where Comparator is useful.

                                                            - Pankaj

                                                              JournalDev
                                                              DigitalOcean Employee
                                                              DigitalOcean Employee badge
                                                              December 18, 2014

                                                              With Java 8, sorting is pretty simple. Let us sort employees according to their age in an employee list: Collections.sort(employeeList, Comparator.comparing(Employee::getAge); This single line does everything…

                                                              - Anoop

                                                                JournalDev
                                                                DigitalOcean Employee
                                                                DigitalOcean Employee badge
                                                                May 27, 2015

                                                                Good explanation on “Comparable & Comparator”.

                                                                - Rajesh

                                                                  JournalDev
                                                                  DigitalOcean Employee
                                                                  DigitalOcean Employee badge
                                                                  June 21, 2015

                                                                  Very useful explanation, I was surfing through lot of pages for proper answer. Finally I got it, Thanks for the article.

                                                                  - Arun@Ar

                                                                    JournalDev
                                                                    DigitalOcean Employee
                                                                    DigitalOcean Employee badge
                                                                    July 28, 2015

                                                                    Nice explanation Sir. Performance wise which is better … Comparable or Comparator ?

                                                                    - Chandra

                                                                      JournalDev
                                                                      DigitalOcean Employee
                                                                      DigitalOcean Employee badge
                                                                      August 2, 2015

                                                                      Awesome article… Very simple and so informative. I love this article. Thank you.

                                                                      - Shikha Virmani

                                                                        JournalDev
                                                                        DigitalOcean Employee
                                                                        DigitalOcean Employee badge
                                                                        August 20, 2015

                                                                        this is really helpful,thanks a lot :)

                                                                        - thanks a lot

                                                                          JournalDev
                                                                          DigitalOcean Employee
                                                                          DigitalOcean Employee badge
                                                                          December 13, 2015

                                                                          Some human come to earth to make things simple and easy :)

                                                                          - Veera

                                                                          JournalDev
                                                                          DigitalOcean Employee
                                                                          DigitalOcean Employee badge
                                                                          December 13, 2015

                                                                          Hey TimeStamp for Los Angeles … Why not IST

                                                                          - Veera

                                                                          JournalDev
                                                                          DigitalOcean Employee
                                                                          DigitalOcean Employee badge
                                                                          December 13, 2015

                                                                          It’s coming from server that is sitting in West Coast time zone.

                                                                          - Pankaj

                                                                            JournalDev
                                                                            DigitalOcean Employee
                                                                            DigitalOcean Employee badge
                                                                            December 13, 2015

                                                                            Thanks Veera, you made my day. Subscribe to my newsletter if you have not done already, you will find more reasons to praise me. :)

                                                                            - Pankaj

                                                                              JournalDev
                                                                              DigitalOcean Employee
                                                                              DigitalOcean Employee badge
                                                                              March 6, 2016

                                                                              highly understandable work, thanks mr. Pankaj I have a problem with print those data in a table, have any easy way to do it?

                                                                              - deshani

                                                                                JournalDev
                                                                                DigitalOcean Employee
                                                                                DigitalOcean Employee badge
                                                                                March 26, 2016

                                                                                I’ve read Java article from different places, I found yours are the best at explaining complex ideas, you always made them easy to understand with really good example, your articles are short but express all the important ideas, thank you for post such high quality articles!

                                                                                - Shuang

                                                                                  JournalDev
                                                                                  DigitalOcean Employee
                                                                                  DigitalOcean Employee badge
                                                                                  July 1, 2016

                                                                                  You made a typing mistake I think, while summarizing at the end. For point 1 and point 2, 1. Comparable interface can be used to provide single way of sorting whereas Comparable interface is used to provide different ways of sorting. 2. For using Comparable, Class needs to implement it whereas for using Comparable we don’t need to make any change in the class. after the word whereas in both points, I think you mean to say “Comparator” instead of “Comparable”.

                                                                                  - Amit

                                                                                  JournalDev
                                                                                  DigitalOcean Employee
                                                                                  DigitalOcean Employee badge
                                                                                  July 1, 2016

                                                                                  Thanks for catching it, i have corrected it.

                                                                                  - Pankaj

                                                                                    JournalDev
                                                                                    DigitalOcean Employee
                                                                                    DigitalOcean Employee badge
                                                                                    July 29, 2016

                                                                                    Thanks Pankaj ! You have simplified many complex ideas regarding collections.

                                                                                    - Sajal Goel

                                                                                    JournalDev
                                                                                    DigitalOcean Employee
                                                                                    DigitalOcean Employee badge
                                                                                    July 31, 2016

                                                                                    Thanks Sajal.

                                                                                    - Pankaj

                                                                                      JournalDev
                                                                                      DigitalOcean Employee
                                                                                      DigitalOcean Employee badge
                                                                                      September 14, 2016

                                                                                      Simply great article.Easy to understand.

                                                                                      - Rupesh Jha

                                                                                        JournalDev
                                                                                        DigitalOcean Employee
                                                                                        DigitalOcean Employee badge
                                                                                        November 12, 2016

                                                                                        wonderful article simple and practical thank you

                                                                                        - shiva

                                                                                          JournalDev
                                                                                          DigitalOcean Employee
                                                                                          DigitalOcean Employee badge
                                                                                          January 28, 2017

                                                                                          Hi Pankaj, Excellent explanation. Hats off to you!! Just found one mistake. In the last section, Comparable vs Comparator you’ve written: “For Comparator, client needs to provide the Comparator class to use in compare() method.” I think it should be: “For Comparator, client needs to provide the Comparator class to use in sort() method.” Correct me if I’m wrong here and please continue the good work.

                                                                                          - Kumar Mayank Singh

                                                                                          JournalDev
                                                                                          DigitalOcean Employee
                                                                                          DigitalOcean Employee badge
                                                                                          January 30, 2017

                                                                                          What I have written is correct. Client class needs to provide which comparator to use. sort() method example uses Comparable.

                                                                                          - Pankaj

                                                                                            JournalDev
                                                                                            DigitalOcean Employee
                                                                                            DigitalOcean Employee badge
                                                                                            April 20, 2017

                                                                                            Hi Pankaj , In 4th point of Comparable vs Comparator I think there is some type error “Collection.sort()” .But Collection is an interface and there is no sort() method in these interface,Instead of Collection there should be Collections method. Because Collections is an utility class and in this class there is a method “Collections.sort()” ---- This method sorts the specified collection. Thanks

                                                                                            - Ashutosh Kumar

                                                                                              JournalDev
                                                                                              DigitalOcean Employee
                                                                                              DigitalOcean Employee badge
                                                                                              April 22, 2017

                                                                                              I’ve been trying to understand this concept from long time and I’m glad to say “Your Explanation” made so clear. splendid . Thank you!

                                                                                              - Ajay

                                                                                                JournalDev
                                                                                                DigitalOcean Employee
                                                                                                DigitalOcean Employee badge
                                                                                                May 17, 2017

                                                                                                i have heard this topic a lot of times this is my first time didn’t took me second read i think the explanation couldn’t have been simpler Great job there Thanks

                                                                                                - Shashank Sharma

                                                                                                  JournalDev
                                                                                                  DigitalOcean Employee
                                                                                                  DigitalOcean Employee badge
                                                                                                  June 13, 2017

                                                                                                  i am not able to understand the line (this.id - emp.id) or this line o1.getId() - o2.getId(); means how here it is comparing between the values please anybody can explain me ???

                                                                                                  - vishwas

                                                                                                  JournalDev
                                                                                                  DigitalOcean Employee
                                                                                                  DigitalOcean Employee badge
                                                                                                  June 30, 2017

                                                                                                  Inside the compiler , it requires a value from your side which is required to determine the natural sorting.It is an understanding internally specific to the java Technology.

                                                                                                  - kathiravan

                                                                                                    JournalDev
                                                                                                    DigitalOcean Employee
                                                                                                    DigitalOcean Employee badge
                                                                                                    July 16, 2017

                                                                                                    Beautiful and detailed explanation. I have been trying to know why and when to use what, I got my answer here. You made it quite simple. I have been referring your latest Interview questions pdf which redirected me here. Thanks a ton!

                                                                                                    - Shweta

                                                                                                      JournalDev
                                                                                                      DigitalOcean Employee
                                                                                                      DigitalOcean Employee badge
                                                                                                      August 9, 2017

                                                                                                      The second Point is not true. ““For using Comparable, Class needs to implement it whereas for using Compactor we don’t need to make any change in the class.”” because we can even use the comparable with out making changes(how we used compactor).

                                                                                                      - Swarna

                                                                                                      JournalDev
                                                                                                      DigitalOcean Employee
                                                                                                      DigitalOcean Employee badge
                                                                                                      September 26, 2017

                                                                                                      The second point is true. We cann’t do below :: Suppose I have a class Employee as shown below - public class Employee { private int id; private String name; private Double salary; private int age; public Employee(int id, String name, Double salary, int age) { super(); this.id = id; this.name = name; this.salary = salary; this.age = age; } public Employee() { // TODO Auto-generated constructor stub } } Now I can’t have another class which implements Comparable interface for Employee. lets suppose we define another class - class AnotherClass implements Comparable{ @Override public int compareTo(Employee o) { // TODO Auto-generated method stub //I can’t use this here. As my compareTo() method demands. return 0; } }

                                                                                                      - Monika

                                                                                                        JournalDev
                                                                                                        DigitalOcean Employee
                                                                                                        DigitalOcean Employee badge
                                                                                                        August 30, 2017

                                                                                                        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 sort based on one field only and we can’t chose the field on which we want to sort the Object"“”" . We can’t chose the field? We can chose one field, right?

                                                                                                        - Raj

                                                                                                        JournalDev
                                                                                                        DigitalOcean Employee
                                                                                                        DigitalOcean Employee badge
                                                                                                        September 26, 2017

                                                                                                        Yes we can. This is written wrong here. We can definitely choose one field in compareTo() method.

                                                                                                        - Monika

                                                                                                        JournalDev
                                                                                                        DigitalOcean Employee
                                                                                                        DigitalOcean Employee badge
                                                                                                        September 27, 2017

                                                                                                        You are not getting the point, what I meant is that once you have provided the implementation of Comparable.compareTo() method, you can’t change it dynamically. For example, let’s say you have Employee class and you implemented compareTo() method to sort based on ID, now you can’t change it dynamically to Salary or Age. This is where Comparator is helpful, you can define multiple Comparators and use them based on your requirement. I hope you got the point now.

                                                                                                        - Pankaj

                                                                                                          JournalDev
                                                                                                          DigitalOcean Employee
                                                                                                          DigitalOcean Employee badge
                                                                                                          November 4, 2017

                                                                                                          Nice explanation , keep posting java articles like this.

                                                                                                          - Subham

                                                                                                            JournalDev
                                                                                                            DigitalOcean Employee
                                                                                                            DigitalOcean Employee badge
                                                                                                            December 4, 2017

                                                                                                            Excellent explanation. Thank you.

                                                                                                            - Pragati

                                                                                                              JournalDev
                                                                                                              DigitalOcean Employee
                                                                                                              DigitalOcean Employee badge
                                                                                                              March 20, 2018

                                                                                                              Nice one. Well explained

                                                                                                              - Shradha

                                                                                                                JournalDev
                                                                                                                DigitalOcean Employee
                                                                                                                DigitalOcean Employee badge
                                                                                                                August 10, 2018

                                                                                                                Can you please explain how the same can be done using List ?

                                                                                                                - Vijayalaxmi

                                                                                                                  JournalDev
                                                                                                                  DigitalOcean Employee
                                                                                                                  DigitalOcean Employee badge
                                                                                                                  September 18, 2018

                                                                                                                  Thanks for a simple and clear explanation of the concept. Cheers

                                                                                                                  - deepak yadav

                                                                                                                    JournalDev
                                                                                                                    DigitalOcean Employee
                                                                                                                    DigitalOcean Employee badge
                                                                                                                    April 14, 2019

                                                                                                                    import java.util.*; public class Item implements Comparable{ public int serialNumber; private String name; private double unitPrice; public Item(int sn, String n, double p) { serialNumber = sn; name = n; unitPrice = p; } public String getName(){ return name; } public double getUnitPrice(){ return unitPrice; } public void setUnitPrice(double p){ unitPrice = p; } public void printDetails(){ System.out.print(“NAME: " + name); System.out.print(” || SERIAL NUMBER: " + serialNumber); System.out.println(" || UNIT PRICE: $" + unitPrice); } ///////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////// /** * Comparator to sort Item in order of unit price * **/ public static ComparatorUnitPriceComparator = new Comparator(){ public int compare(Item n1,Item n2) { return(int) (n1.getUnitPrice()-n2.getUnitPrice()); } }; ///////////////////////////////////////////////////////////////////////////////// /** * Comparator to sort Items in order of their names * **/ public static ComparatorNameComparator= new Comparator() { public int compare(Item name1, Item name2) { return name1.getName().compareTo(name2.getName()); } }; } I got an error after executing this code … please help $javac Item.java Item.java:2: error: Item is not abstract and does not override abstract method compareTo(Item) in Comparable public class Item implements Comparable{ ^ 1 error

                                                                                                                    - Student

                                                                                                                    JournalDev
                                                                                                                    DigitalOcean Employee
                                                                                                                    DigitalOcean Employee badge
                                                                                                                    April 19, 2019

                                                                                                                    Your Item class implements the comparable interface , so override compareTo() method here . I can see the Item class has not the compareTo() method. Thanks

                                                                                                                    - Niharika

                                                                                                                      JournalDev
                                                                                                                      DigitalOcean Employee
                                                                                                                      DigitalOcean Employee badge
                                                                                                                      May 4, 2019

                                                                                                                      Comparable vs Comparator At Point 4 : It should be Collections.sort() and not Collection.sort()

                                                                                                                      - Sagar

                                                                                                                      JournalDev
                                                                                                                      DigitalOcean Employee
                                                                                                                      DigitalOcean Employee badge
                                                                                                                      September 4, 2020

                                                                                                                      Woow Super

                                                                                                                      - TEST

                                                                                                                        JournalDev
                                                                                                                        DigitalOcean Employee
                                                                                                                        DigitalOcean Employee badge
                                                                                                                        July 30, 2019

                                                                                                                        Why can’t i use Comparable like this for different of Sortings… public static Comparable SalaryComparable = new Comparable() { @Override public int compareTo(Employee e) { return (int) (this.getSalary() - e.getSalary()); } }; public static Comparable AgeComparable = new Comparable() { @Override public int compareTo(Employee e) { return (int) (this.getAge() - e.getAge()); } };

                                                                                                                        - Ram

                                                                                                                        JournalDev
                                                                                                                        DigitalOcean Employee
                                                                                                                        DigitalOcean Employee badge
                                                                                                                        October 21, 2019

                                                                                                                        What would be ‘this’ in this case? You can’t have access to a non-static member in a static class, so this wouldn’t work.

                                                                                                                        - Mike

                                                                                                                          JournalDev
                                                                                                                          DigitalOcean Employee
                                                                                                                          DigitalOcean Employee badge
                                                                                                                          August 12, 2020

                                                                                                                          No, you can not use like this way because, sort() method takes input of Comparator type not Camparable type. So you can not use your “SalaryComparable” or “AgeComparable” anywhere.

                                                                                                                          - Susovan Maji

                                                                                                                            JournalDev
                                                                                                                            DigitalOcean Employee
                                                                                                                            DigitalOcean Employee badge
                                                                                                                            January 9, 2020

                                                                                                                            Nice work Pankaj. I always comeback whenever there is need to refresh.

                                                                                                                            - Manish

                                                                                                                              JournalDev
                                                                                                                              DigitalOcean Employee
                                                                                                                              DigitalOcean Employee badge
                                                                                                                              January 28, 2021

                                                                                                                              Hi Pankaj, Since Comparable is an interface and any class which implements the interface should override all the methods, then why “Employee implements Comparable” only overrides the “compare” method. Don’t we need to override all the abstract methods in Comparable? Thanks

                                                                                                                              - Kalyan Ghosh

                                                                                                                                JournalDev
                                                                                                                                DigitalOcean Employee
                                                                                                                                DigitalOcean Employee badge
                                                                                                                                June 15, 2021

                                                                                                                                You made this really easy. It’s no longer over my head anymore. Thanks !

                                                                                                                                - Xhunter

                                                                                                                                  Try DigitalOcean for free

                                                                                                                                  Click below to sign up and get $200 of credit to try our products over 60 days!

                                                                                                                                  Sign up

                                                                                                                                  Join the Tech Talk
                                                                                                                                  Success! Thank you! Please check your email for further details.

                                                                                                                                  Please complete your information!

                                                                                                                                  Become a contributor for community

                                                                                                                                  Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

                                                                                                                                  DigitalOcean Documentation

                                                                                                                                  Full documentation for every DigitalOcean product.

                                                                                                                                  Resources for startups and SMBs

                                                                                                                                  The Wave has everything you need to know about building a business, from raising funding to marketing your product.

                                                                                                                                  Get our newsletter

                                                                                                                                  Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

                                                                                                                                  New accounts only. By submitting your email you agree to our Privacy Policy

                                                                                                                                  The developer cloud

                                                                                                                                  Scale up as you grow — whether you're running one virtual machine or ten thousand.

                                                                                                                                  Get started for free

                                                                                                                                  Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

                                                                                                                                  *This promotional offer applies to new accounts only.