Comparable and Comparator in Java Example

Filed Under: Java

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.

Comments

  1. Ram says:

    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());
    }
    };

    1. Mike says:

      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.

  2. Sagar says:

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

  3. Student says:

    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

    1. Niharika says:

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

  4. deepak yadav says:

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

  5. Vijayalaxmi says:

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

  6. Shradha says:

    Nice one. Well explained

  7. Pragati says:

    Excellent explanation. Thank you.

  8. Subham says:

    Nice explanation , keep posting java articles like this.

  9. Raj says:

    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?

    1. Monika says:

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

      1. Pankaj says:

        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.

        1. krish says:

          Perhaps, You need to correct the wording. Even, I thought that we can do with only one field/property. Something like “With Comparable interface we can do only default sorting” would be helpful.

          1. Raja says:

            Right,

            this should fix the wording “..method implementation can sort based on one field only and we can’t frequently dynamically change that one field on which we want to sort the Object.”

            I assume, Mr Pankaj is adamant/ignorant? for someone has pointed his wording wrong 🙂

          2. Pankaj says:

            I have changed the wordings to make it more clear. I am always happy to take constructive feedback and improve the article.

  10. Swarna says:

    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).

    1. Monika says:

      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;
      }
      }

  11. Shweta says:

    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!

  12. vishwas says:

    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 ???

    1. kathiravan says:

      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.

  13. Shashank Sharma says:

    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

  14. Ajay says:

    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!

  15. Ashutosh Kumar says:

    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

  16. Kumar Mayank Singh says:

    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.

    1. Pankaj says:

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

  17. shiva says:

    wonderful article
    simple and practical
    thank you

  18. Rupesh Jha says:

    Simply great article.Easy to understand.

  19. Sajal Goel says:

    Thanks Pankaj !

    You have simplified many complex ideas regarding collections.

  20. Amit says:

    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”.

    1. Pankaj says:

      Thanks for catching it, i have corrected it.

  21. Shuang says:

    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!

  22. deshani says:

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

  23. Veera says:

    Some human come to earth to make things simple and easy 🙂

    1. Veera says:

      Hey TimeStamp for Los Angeles … Why not IST

      1. Pankaj says:

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

    2. Pankaj says:

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

  24. thanks a lot says:

    this is really helpful,thanks a lot 🙂

  25. Shikha Virmani says:

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

  26. Chandra says:

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

  27. Arun@Ar says:

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

  28. Rajesh says:

    Good explanation on “Comparable & Comparator”.

  29. Anoop says:

    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…

  30. Raghav says:

    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.

    1. Pankaj says:

      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.

  31. Sridhar says:

    Excellent Explanation

  32. madan says:

    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
    }

  33. Atmprakash Sharma says:

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

  34. Niraj kumar singh says:

    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.

    1. Pankaj says:

      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.

  35. Niranjan says:

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

  36. satya says:

    nice explanations

  37. triggergirl says:

    Perfect Explanation .Really it makes me to understand easily

  38. Andy says:

    Best explanation ever. . Thanks 🙂

  39. indu says:

    good nice article

  40. indu says:

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

  41. Yogesh Pal says:

    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.

  42. Manash Ranjan Dakua says:

    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.

    1. suraj says:

      superb!!!

  43. prateek says:

    cleared concept…Amazing work SiR thnxx 🙂

  44. Raj says:

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

    1. Pankaj says:

      You will have to use the String sorting options.

  45. kamaljit says:

    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,

    1. Pankaj says:

      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.

  46. Sandy says:

    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

    1. Pankaj says:

      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.

  47. Muralidhar N says:

    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 ..

    1. Pankaj says:

      yeah right, changed the program.

      Thanks for spotting it.

  48. Nagesh kaniganti says:

    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……….

  49. Roshan says:

    very nicely written.

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages