Skip to main content

Java Sorting: Comparator vs Comparable Tutorial

Java Comparators and Comparables? What are they? How do we use them? This is a question we received from one of our readers. This article will discuss the java.util.Comparator and java.lang.Comparable in details with a set of sample codes for further clarifications.

Prerequisites

  • Basic Java knowledge

System Requirements

  • JDK installed

What are Java Comparators and Comparables?

As both names suggest (and you may have guessed), these are used for comparing objects in Java. Using these concepts; Java objects can be sorted according to a predefined order.
Two of these concepts can be explained as follows.

Comparable

A comparable object is capable of comparing itself with another object. The class itself must implements the java.lang.Comparable interface in order to be able to compare its instances.

Comparator

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

Do we need to compare objects?

The simplest answer is yes. When there is a list of objects, ordering these objects into different orders becomes a must in some situations. For example; think of displaying a list of employee objects in a web page. Generally employees may be displayed by sorting them using the employee id. Also there will be requirements to sort them according to the name or age as well. In these situations both these (above defined) concepts will become handy.

How to use these?

There are two interfaces in Java to support these concepts, and each of these has one method to be implemented by user. Those are;
java.lang.Comparable: int compareTo(Object o1)
This method compares this object with o1 object. Returned int value has the following meanings.
  1. positive – this object is greater than o1
  2. zero – this object equals to o1
  3. negative – this object is less than o1
java.util.Comparator: int compare(Object o1, Objecto2)
This method compares o1 and o2 objects. Returned int value has the following meanings.
  1. positive – o1 is greater than o2
  2. zero – o1 equals to o2
  3. negative – o1 is less than o2

Sorting with Collections class

  • java.util.Collections.sort(List) and java.util.Arrays.sort(Object[]) methods can be used to sort using natural ordering of objects.
  • java.util.Collections.sort(List, Comparator) and java.util.Arrays.sort(Object[], Comparator) methods can be used if a Comparator is available for comparison.
The above explained Employee example is a good candidate for explaining these two concepts. First we’ll write a simple Java bean to represent the Employee.
public class Employee {
    private int empId;
    private String name;
    private int age;

    public Employee(int empId, String name, int age) {
        // set values on attributes
    }
    // getters & setters
}
Next we’ll create a list of Employees for using in different sorting requirements. Employees are added to a List without any specific order in the following class.
import java.util.*;

public class Util {

    public static List<Employee> getEmployees() {

        List<Employee> col = new ArrayList<Employee>();

        col.add(new Employee(5, "Frank", 28));
        col.add(new Employee(1, "Jorge", 19));
        col.add(new Employee(6, "Bill", 34));
        col.add(new Employee(3, "Michel", 10));
        col.add(new Employee(7, "Simpson", 8));
        col.add(new Employee(4, "Clerk",16 ));
        col.add(new Employee(8, "Lee", 40));
        col.add(new Employee(2, "Mark", 30));

        return col;
    }
}

Sorting in natural ordering

Employee’s natural ordering would be done according to the employee id. For that, above Employee class must be altered to add the comparing ability as follows.
public class Employee implements Comparable<Employee> {
    private int empId;
    private String name;
    private int age;

    /**
    * Compare a given Employee with this object.
    * If employee id of this object is 
    * greater than the received object,
    * then this object is greater than the other.
    */
    public int compareTo(Employee o) {
        return this.empId - o.empId ;
    }
    // ….
}
The new compareTo() method does the trick of implementing the natural ordering of the instances. So if a collection of Employee objects is sorted using Collections.sort(List) method; sorting happens according to the ordering done inside this method.

We’ll write a class to test this natural ordering mechanism. Following class use the Collections.sort(List) method to sort the given list in natural order.
import java.util.*;

public class TestEmployeeSort {

    public static void main(String[] args) {     
        List coll = Util.getEmployees();
        Collections.sort(coll); // sort method
        printList(coll);
    }

    private static void printList(List<Employee> list) {
        System.out.println("EmpId\tName\tAge");
        for (Employee e: list) {
            System.out.println(e.getEmpId() + "\t" + e.getName() + "\t" + e.getAge());
        }
    }
}
Run the above class and examine the output. It will be as follows. As you can see, the list is sorted correctly using the employee id. As empId is an int value, the employee instances are ordered so that the int values ordered from 1 to 8.
EmpId Name Age
1 Jorge 19
2 Mark 30
3 Michel 10
4 Clerk 16
5 Frank 28
6 Bill 34
7 Simp 8
8 Lee 40

Sorting by other fields

If we need to sort using other fields of the employee, we’ll have to change the Employee class’s compareTo() method to use those fields. But then we’ll loose this empId based sorting mechanism. This is not a good alternative if we need to sort using different fields at different occasions. But no need to worry; Comparator is there to save us.

By writing a class that implements the java.util.Comparator interface, you can sort Employees using any field as you wish even without touching the Employee class itself; Employee class does not need to implement java.lang.Comparable or java.util.Comparator interface.

Sorting by name field

Following EmpSortByName class is used to sort Employee instances according to the name field. In this class, inside the compare() method sorting mechanism is implemented. In compare() method we get two Employee instances and we have to return which object is greater.
public class EmpSortByName implements Comparator<Employee>{

    public int compare(Employee o1, Employee o2) {
        return o1.getName().compareTo(o2.getName());
    }
}
Watch out: Here, String class’s compareTo() method is used in comparing the name fields (which are Strings).

Now to test this sorting mechanism, you must use the Collections.sort(List, Comparator) method instead of Collections.sort(List) method. Now change the TestEmployeeSort class as follows. See how the EmpSortByName comparator is used inside sort method.
import java.util.*;

public class TestEmployeeSort {

    public static void main(String[] args) {

        List coll = Util.getEmployees();
        //Collections.sort(coll);
        //use Comparator implementation
        Collections.sort(coll, new EmpSortByName());
        printList(coll);
    }

    private static void printList(List<Employee> list) {
        System.out.println("EmpId\tName\tAge");
        for (Employee e: list) {
            System.out.println(e.getEmpId() + "\t" + e.getName() + "\t" + e.getAge());
        }
    }
}
Now the result would be as follows. Check whether the employees are sorted correctly by the name String field. You’ll see that these are sorted alphabetically.
EmpId Name Age
6 Bill 34
4 Clerk 16
5 Frank 28
1 Jorge 19
8 Lee 40
2 Mark 30
3 Michel 10
7 Simp 8

Sorting by empId field

Even the ordering by empId (previously done using Comparable) can be implemented using Comparator; following class does that.
public class EmpSortByEmpId implements Comparator<Employee>{

    public int compare(Employee o1, Employee o2) {
        return o1.getEmpId() - o2.getEmpId();
    }
}

Explore further

Do not stop here. Work on the followings by yourselves and sharpen knowledge on these concepts.
  1. Sort employees using name, age, empId in this order (ie: when names are equal, try age and then next empId)
  2. Explore how & why equals() method and compare()/compareTo() methods must be consistence.
If you have any issues on these concepts; please add those in the comments section and we’ll get back to you.

Related Articles

Comments

  1. You should also try to handle null values.

    When dealing with comparable and comparator NPE is near far.

    ReplyDelete
    Replies

    1. True, there will be situations where you caught up with NPE. But I don't think this responsibility is bound to Comparator or Comparable.

      For example; if we are using String class to sort, it's our duty to deal with the 'null' values. String class will through NPE if 'null' values used.

      But it would be good if we could handle that as well.

      Delete
  2. Languages which support closures can often make this sort of task easy, e.g. Groovy:

    class Employee implements Comparable<Employee> {
      def empId, name, age
      Employee(e, n, a) { empId=e; name=n; age=a }
      int compareTo(other) { empId - other.empId }
    }

    employees = [
      new Employee(5, "Frank", 28),
      new Employee(1, "Jorge", 19),
      new Employee(6, "Bill", 34),
      new Employee(3, "Michel", 10),
      new Employee(7, "Simpson", 8),
      new Employee(4, "Clerk", 16),
      new Employee(8, "Lee", 40),
      new Employee(2, "Mark", 30)
    ]

    pretty = { println "EmpId\tName\tAge"; it.each{ println "$it.empId\t$it.name\t$it.age" } }
    pretty employees.sort()
    pretty employees.sort{ it.name }
    pretty employees.sort{ it.age }

    ReplyDelete
  3. And just to complete the example, a manually defined comparator:

    byNameLength = { a, b -> a.name.size() <=> b.name.size() } as Comparator
    pretty employees.sort(byNameLength)

    ReplyDelete
  4. this is good just what I looked for.

    cheers
    Nimch

    ReplyDelete
  5. The context in which comparable or comparator should be used is pretty clear, good tutorial

    ReplyDelete
  6. Exactly what I was looking for to get ready for exam
    Thank you very much

    ReplyDelete
  7. This tutorial is short, concise and crystal clear.
    I'm a undergraduate student learning Java and this helped me set some things I didn't understand straight.
    Thanks !

    ReplyDelete
  8. Nice one. Very helpful...

    ReplyDelete
  9. This is very helpful.

    ReplyDelete
  10. Good example.
    But this code working just for Java 5 and higher .
    But for some reason I need to use Java 1.4. Next the same code for Java 1.4: It looks like:
    1. public class Employee implements Comparable{
    2. public int compareTo(Object o) {
    Employee e = new Employee();
    e = (Employee)o;
    return this.empId - e.getEmpId() ;
    3. public class EmpSortByName implements Comparator{
    public int compare(Object o1, Object o2) {
    Employee e1 = new Employee();
    e1 = (Employee)o1;
    Employee e2 = new Employee();
    e2 = (Employee)o2;
    return e1.getName().compareTo(e2.getName());

    Thanks
    Igor Chirokov

    ReplyDelete
  11. 1.In this list I have multiple elements and I'm needing to sort by 2 elements within this list: first by binSortCode and then by itemDescr

    I've been googling and trying to get some help but am having problems trying to understanding comparable vs comparator. I had used comparable to sort on a single element and it worked find but when trying to sort on multiple elements I'm not able to make it work.

    I have created a comparator class where I am trying to sort first on binSortCode and then sort on itemDesc, please see the following:

    public class CommonListItemSort implements Comparator$ltCommonListItem&gt{
    2.
    3. //Sort common list items by bin sort code then by item description
    4. public int compare(CommonListItem o1, CommonListItem o2) {
    5. int diff = o1.getBinSortCode().compareToIgnoreCase(o2.getBinSortCode());
    6. if (diff == 0)
    7. diff = o1.getItemDesc().compareToIgnoreCase(o2.getItemDesc());
    8. return diff;
    11. }
    12. }
    13.
    14. I then call this class from my servicebean as follows:
    15.
    16. public CommonList getDetails(final String entityCode, final String commonListName) {
    17. CommonList commonList = commonListDao.find(commonListName, entityCode);
    18.
    19. //Sort the items by binsortcode and then by item description
    20. Collections.sort(commonList.getCommonListItems(), new CommonListItemSort());
    21. return commonList;
    22. }

    The outcome that I'm getting is that binSortCode is in DESC order and itemDesc is in ASC order where in actuality I need the list to sort first by binSortCode ASC and then itemDesc in ASC.

    Any help or direction would be greatly appreciated. Thanks.

    ReplyDelete
  12. return o1.getEmpId().compareTo(o2.getEmpId()); in class EmpSortByEmpId doesn't compile.
    Solution : compare Strings !
    return String.valueOf(o1.getEmpId()).compareTo(String.valueOf(o2.getEmpId()));

    ReplyDelete
  13. Real good thanks! Im getting ready for exam and this was so much clearer than the PDF we was handen. Cheers

    ReplyDelete
  14. Typo above:
    negative – o1 is less than o1

    should be
    negative – o1 is less than o2

    ReplyDelete
  15. I'd like to add my thanks as well.

    Your examples were very concise and clear. They helped me actually implement Comparator as opposed to just understanding the theory.

    ReplyDelete
  16. Thanks, Really a good tutorial.

    ReplyDelete
  17. Thanks, Its really good artical to understand and well explained.

    ReplyDelete
  18. it was very usefull....thanks a lot

    ReplyDelete
  19. Good one was very useful!

    appreciate ur effort !

    ReplyDelete
  20. very nice!
    thank you!

    ReplyDelete
  21. very nice and clean!
    Thank You very much.

    ReplyDelete
  22. it very clear thank u very much

    ReplyDelete
  23. Good tutorial ,
    However on execution of the code gives me "Class Cast Exception" ,
    java.lang.ClassCastException: com.Comparator.Employee cannot be cast to java.lang.Comparable

    Can anyone suggest

    ReplyDelete
  24. this really helped

    ReplyDelete
  25. Nice one !!! It would be helpful to everyone

    ReplyDelete
  26. This was the best article. Very, very helpful, nice and clean.

    ReplyDelete
  27. Excellent explanation, thanks much.

    Don

    ReplyDelete
  28. easy, concise, simple and an accurate example. Thanks Kamal

    ReplyDelete
  29. He has written a very good article . Instead of pointing out mistakes , appreciate his efforts & provide better suggestions. Great Job

    ReplyDelete
  30. Thanks a lot. Very useful tutorial. Vladimir

    ReplyDelete
  31. Very nice,easily understandable,
    and please give the why we have to override hashcode() method.

    ReplyDelete
  32. To the point and precise. Great work!!

    ReplyDelete
  33. This tutorial was fantastic. I knew I needed to use a Comparator, but it's been a long time since I last did one. This information was exactly what I needed to get the job done and jogged my brain again.

    Thank you and keep the tutorials coming!

    ReplyDelete
  34. you have written in definition of the Comparator that it belongs to java.lang.comparator but it is wrong and instead it belongs to java.util.comparator;

    ReplyDelete
  35. thanks for a clean tutorial. I get it now !

    -Omaha, Nebraska (USA)

    ReplyDelete
  36. Is there any way to include more than one method in a single class, rather than creating single compare method in one class

    ReplyDelete
  37. nice explaination! Just one correction - Comparator interface is under java.util package and not under java.lang

    ReplyDelete
  38. Thank you! I have been searching for hours how to sort my ArrayList and only your tutorial made me understand what I was doing wrong (my ArrayList was made of arrays, as in ArrayList«double[]»).

    A well written tutorial, thanks again!

    ReplyDelete
  39. Good example............. Yeah I got the point.. Thank you very much :) cheers

    ReplyDelete
  40. really nice explanation.. hats off

    ReplyDelete
  41. good article! thanks!

    ReplyDelete
  42. veeeeeeeeeeerrrrrry helpful, thorough, and well written, thanks.

    Allasso

    ReplyDelete
  43. Thanks for your effort!It is really good!
    However ,I found that the last part "Sorting by empId field" does not work !
    I have to cast the int into String first,
    public class EmpSortByEmpId implements Comparator{

    public int compare(Employee o1, Employee o2) {
    String myStringO1 = Integer.toString(o1.getEmpId());
    String myStringO2 = Integer.toString(o2.getEmpId());
    return myStringO1.compareTo(myStringO2);
    }

    ReplyDelete
  44. // 42
    Hi fan,

    You will not need to convert int values to Strings in this example as Java5 does auto-boxing.

    ReplyDelete
  45. The explanation is super. thanks.

    ReplyDelete
  46. This really helped in my preparation about Comparable and Comparator. Well framed I book marked.

    ReplyDelete
  47. Hi,

    Very Nice article..It made me very clear abt the Comparable and Comparator interface.. I had checked few sites..but there was no clear info as you have provided.. Thanks

    ReplyDelete
  48. Thank you for taking the time to publish this, it was very clear. The best basic tutorial on comparator I have seen!

    ReplyDelete
  49. Thank you so much ! I found what I was looking for !!
    Thanks From Paris (France).

    ReplyDelete
  50. Your post help me a lot.
    thanks from Brazil!

    ReplyDelete
  51. thank you . I from vietnamese

    ReplyDelete
  52. Thank you....Very clearly explained

    ReplyDelete
  53. Good information in precise form

    ReplyDelete
  54. Simply simple in simple terms... the basic context of both interfaces is clear

    ReplyDelete
  55. thax a lot dude...very useful tutorial....thanx again

    Prabhat

    ReplyDelete
  56. very nice... and helpful. thks biju

    ReplyDelete
  57. hi can u plz tell me why equals() and compare()methods must be consistence

    ReplyDelete
  58. Hello Kamal,
    One very important correction needs to be made to this post. Comparator belongs to the java.util package and not java.lang as you have mentioned in the beginning of the post. Please rectify as this a crucial thing to be overlooked.

    regards,
    Aparajeeta

    ReplyDelete
  59. this is very helpful tutorial. really good one

    ReplyDelete
  60. Hello Kamal,
    It is simple and very helpful.
    one Imp.note I too observed that the comparator interface is from java.util, but is is mentioned as from java.lang in the beginning (How to use these? section).

    Thank you.
    Santhosh

    ReplyDelete
  61. Very Clear. Thank You.

    ReplyDelete
  62. Thanks for your effort!It is really good!
    However ,I found that the last part "Sorting by empId field" does not work !
    I have to cast the int into String first,
    I'm Using java 1.5 , but it's not auto boxing. I mean int to String.
    compateTo() method compares only Strings only
    public class EmpSortByEmpId implements Comparator{

    public int compare(Employee o1, Employee o2) {
    String myStringO1 = Integer.toString(o1.getEmpId());
    String myStringO2 = Integer.toString(o2.getEmpId());
    return myStringO1.compareTo(myStringO2);
    }

    ReplyDelete
  63. very good explain nation.Really Good..Keep up the Good Work Going....

    ReplyDelete
  64. I must read your other articles. Its nice article.

    ReplyDelete
  65. Here,Collections are used for comparing the different instances but....for the same class. Why so??

    ReplyDelete
  66. Hi,

    Can u plz tell me why equals() and compare()methods must be consistence??

    Regards,
    Bibhakar.

    ReplyDelete
  67. Great, to the point post. Nice way of covering too with good examples.

    ReplyDelete
  68. Hi,

    The Comparator interface belongs to java.util.Hence please correct the article as java.util.Comparator.I think it is a typo.

    ReplyDelete
  69. This is excellence tutorial for beginners to understand the d/f b/w comparable and comparator...Excellent job

    ReplyDelete
  70. This is really great tutorial with nice example. Thanx a lot

    ReplyDelete
  71. wat's d difference between compare() and compareTo() methods

    ReplyDelete
  72. Comparator belongs to util package.....Not to lang........

    ReplyDelete
  73. Hi,
    There is a typo
    java.lang.Comparator,
    instead
    java.util.Comparator

    ReplyDelete
  74. Hi all,
    Thanks for pointing the typo in package name of java.util.Comparator interface. Now it is corrected.

    ReplyDelete
  75. Thank you so much for the explanation and examples, its really helps me. Only that..i got error..java.lang.ClassCastException: java.lang.String cannot be cast to..when i tried to make sorting with integer by following example Sorting by empId field. Can anybody help me? Thank you.

    ReplyDelete
  76. I have menu order as string with levels separated with dot (for instance it will be like 1.2.1 and 1.2.2). This works fine with a sql order by when the last numbers are upto 9 but with 10 it comes as first. After i read ur article i was able to crack it.

    Thanks

    ReplyDelete
  77. Very clear explanation of how comparator and comparable work with nice examples, thank you so much and keep posting more articles like this.

    ReplyDelete
  78. Excellent example.. very well explained...`

    ReplyDelete
  79. i have a problem with this code which most of it have almost same error.help me anyone

    public interface Comparable{
    public int compareTo(Object o);

    }
    public class BinarySearch1{

    public static final boolean contains(Comparable item, Comparable[] array, int n){
    int low = 0;
    int high = n - 1;
    while (low <= high){
    int mid = (low + high) / 2;
    int compare = item.compareTo (array[mid]);
    if (compare < 0){
    high = mid - 1;
    }
    else if (compare > 0){
    low = mid + 1;
    }
    else {
    return true;
    }
    }
    return false;
    }
    public static void main(String[]args){
    BinarySearch1 value = new BinarySearch1();

    Comparable[] array = new Comparable[4];

    //array[0] = new Comparable();

    // System.out.println(value.contains(3,array[1],4));
    //System.out.println(value.contains(4));
    }
    }

    ReplyDelete
  80. really good one.. thanks a lot

    ReplyDelete
  81. Thanks for this great explanation. I've always had trouble understanding the comparator mechanisms until now.

    ReplyDelete
  82. ('=')
    Really Superb Explaination..
    i searchd in many websites...i didnt seen this type of good explaination..
    thank u very much
    All izz well('=')

    ReplyDelete
  83. I was able to implement the same things. Thank you for this :)

    ReplyDelete
  84. Thanks alot ...Very clear and easy to understand :)

    ReplyDelete
  85. I implemented the same code... It works

    ReplyDelete
  86. One of THE best tutorial..

    ReplyDelete
  87. Nice and simple tutorial, thanks!

    ReplyDelete
  88. Awesome explanation, very useful contents.

    ReplyDelete
  89. I have one Employee Class and adding the Employee object in HashSet.
    I am getting the Exception while trying to print the the HashSet in sorted order.
    It works when i use compareTo() but throws exception "Employee cannot be cast to java.lang.Comparable" using compare(). Please help.

    Below is the code:

    public class Employee {
    private String empID;
    private String name;
    private int salary;

    Employee(String empID,String name,int salary){
    this.empID=empID;
    this.name=name;
    this.salary=salary;
    }
    String getName(){
    return name;
    }

    String getEmpID(){
    return empID;
    }

    int getSalary(){
    return salary;
    }

    public String toString(){
    return empID + " " + name + " " + salary;
    }
    }





    import java.util.Collections;
    import java.util.Comparator;
    import java.util.HashSet;
    import java.util.Iterator;
    import java.util.Set;
    import java.util.TreeSet;

    class EmpsortByName implements Comparator{
    public int compare(Employee emp1, Employee emp2){
    return ((emp1.getName()).compareTo(emp2.getName()));
    }
    }

    class EmpsortByID implements Comparator{
    public int compare(Employee emp1, Employee emp2){
    return ((emp1.getEmpID()).compareTo(emp2.getEmpID()));
    }
    }

    class EmpsortBySalary implements Comparator{
    public int compare(Employee emp1, Employee emp2){
    return emp1.getSalary()- emp2.getSalary();
    }
    }

    public class EmployeeHashSet{

    public static void main(String []asgs){

    Set empset = new HashSet();

    empset.add(new Employee("emp1011","Andrew", 30000));
    empset.add(new Employee("emp1021","Stuart", 20000));
    empset.add(new Employee("emp5043","Symond", 40000));
    empset.add(new Employee("emp1010","Rob", 30700));
    empset.add(new Employee("emp1020","Bill", 20900));
    empset.add(new Employee("emp5053","Bill",41000));

    TreeSet setlist=new TreeSet(empset);
    Collections.sort(new ArrayList(setlist),new EmpsortByName());

    Iterator iterator = setlist.iterator();
    System.out.println("\\Employee names in sorted order::");

    while(iterator.hasNext()){
    Employee emp= (Employee)iterator.next();
    System.out.println(emp.getName());
    System.out.println(emp);
    }

    }

    }

    ReplyDelete
  90. Ahh, this tutorial was so crystal clear, nice and small compared to the dreadfully long and complex code examples in my thick java book. Thank you! :)

    ReplyDelete
  91. Very good example..

    ReplyDelete
  92. Terrific.I like the way u explained.thank u so much......

    ReplyDelete
  93. thanks a lot for this tutorial. it was very helpful

    ReplyDelete
  94. Thank you very much, It was really helpful, thanks for your time

    ReplyDelete
  95. This comment has been removed by a blog administrator.

    ReplyDelete
  96. Nicely framed example. good job

    ReplyDelete
  97. hey pls give short n simplest small prg which can be copy n implemented....

    ReplyDelete
  98. Its really helpfull

    ReplyDelete
  99. very nice tutorial... easy to understand the content..
    thanks
    Velu

    ReplyDelete
  100. So clean; but I have a question for you. Since Comparators would be added for each field and newer fields, I was kind of thinking if we can come up with Generic Comparator, like one for Employee, another for Car. I can think of capturing field name into the comparator, using reflection build that getter method, and it should work I believe.

    ReplyDelete
  101. thanks
    regards gaurav g.

    ReplyDelete
  102. Wow, thanks a lot for clearing this up, you saved me hours of time.

    ReplyDelete
  103. Sushanta DuttaJune 22, 2011 2:11 PM

    why equals() should be override in the context of Comparator/Comparable?? please send me the details discussion.

    ReplyDelete
  104. It's really Good

    ReplyDelete
  105. I don't understand the consistency between compare(),compareTo(), and equals().

    ReplyDelete
  106. Good article.

    ReplyDelete
  107. thanks...simple bt helpful

    ReplyDelete
  108. Good example, clearly explained.

    ReplyDelete
  109. nice one. Able to clearly understand the concept.

    ReplyDelete
  110. We are using Java 6 and in our case employee name may be alphanumeric... after sorting names the sorted would be like this e.g. 120,180,200,60,Ashok,Bindu.
    The desired order cann be 60,120,180...
    How can i use comparator in my application..

    ReplyDelete
  111. // 112.
    When a field is alphanumeric, I assume you are representing that using a String. However when sorting you want to sort the values treating numeric values as numeric.
    So it would be easy for you to first check whether the String contains only digits and do number base sort first and String based sort for the rest.

    To find whether a String contains digits; Character.isDigit() method will help.

    http://lkamal.blogspot.com/2008/07/java-numbers-only-string-remove-non.html

    ReplyDelete
  112. Very nicely explained :):)Thanks

    ReplyDelete
  113. Thank you very helpful!

    ReplyDelete
  114. This really helps me a lot, thank you!!!

    ReplyDelete
  115. This is a great tutorial. Thank You!

    ReplyDelete
  116. Hi...This is nice blog..thank you for this information..It helped me...+1ed it.

    ReplyDelete
  117. Employee class/bean is written twice and it has the different code, which one is supposed to be used for this or else how the packaginge need to be done for running the example, pl guide

    Anil

    ReplyDelete
  118. nice and short tutorial, cleared all my doubts

    ReplyDelete
  119. Excellent demo.

    ReplyDelete
  120. Great Job done. :)
    Keep posting more articles.!

    ReplyDelete
  121. if I want to sort empname basis then its working.if empname are same then sorting it according to designation both empname and designation fields are string.plz answer.

    ReplyDelete
  122. I have menu order as string with levels separated with dot (for instance it will be like 1.2.1 and 1.2.2). This works fine with a sql order by when the last numbers are upto 9 but with 10 it comes as first. After i read ur article i was able to crack it.

    Thanks

    ReplyDelete
  123. Thanks a lot! very informative and precise! from Sri lanka :)

    ReplyDelete
  124. Wonderfully You have given your Explanation.Excellent

    ReplyDelete
  125. Very nice explanation. Good job...

    ReplyDelete
  126. Super... lolved It..:)

    ReplyDelete
  127. Well done. This is a brilliant tutorial. So simply explains the differences between the comparable and comparator interfaces. The comparable example is superb for comparing string and integral based attributes for a custom class. It's very simple to apply this example. Oh yeah, the Comparator explanation and example is quintessential as well. Keep up the great work. Fantastic stuff. These things are extremely simple to understand, but it all goes down to how well it is explained.

    ReplyDelete
  128. @134: Thanks a lot for your encouraging comment. Really appreciate it.

    ReplyDelete
  129. Hi..

    Question:In List have no.of obj's so my requirement is in List can remove one or more objs without using any loop and Iterator ? so what is the conclusion..?

    if any is know the answer send me to my mail plz.....(yellappa313@gmail.com)

    ReplyDelete
  130. Really nice article..so simple yet very informative.

    ReplyDelete
  131. Hi..
    Question:How can you remove duplicate element from string?
    Plz send me this Q's answer. My mail(mca.snayak@gmail.com)

    ReplyDelete
  132. Thank you! Now I know the difference

    ReplyDelete
  133. Thanks Nice One

    ReplyDelete
  134. Thank you for your explain...

    ReplyDelete
  135. thanks, your post helped me a lot.

    ReplyDelete
  136. Very good article, i can say best one to understand comparable and comparator

    ReplyDelete
  137. How to compare list objects two fields separetly i.e 1.name,branch 2.marks,name can any body have idea about this?i tried this but no use i cant override compareTo() method

    ReplyDelete
  138. Thanks for this article, very easy to understand.

    ReplyDelete
  139. Thank you for another essential article. Where else could anyone get that kind of information in such a complete way of writing? I have a presentation incoming week, and I am on the lookout for such information.

    ReplyDelete
  140. Thanks for this article, this is really very easy to understand...

    ReplyDelete
  141. Thanks a lot. I was very much confused with two concepts when to use what.Amazing!!!

    ReplyDelete
  142. Nice explanation.....thanks a lot

    ReplyDelete
  143. This comment has been removed by a blog administrator.

    ReplyDelete
  144. This comment has been removed by a blog administrator.

    ReplyDelete
  145. This comment has been removed by a blog administrator.

    ReplyDelete
  146. This comment has been removed by a blog administrator.

    ReplyDelete
  147. This comment has been removed by a blog administrator.

    ReplyDelete
  148. This comment has been removed by a blog administrator.

    ReplyDelete
  149. This comment has been removed by a blog administrator.

    ReplyDelete
  150. This comment has been removed by a blog administrator.

    ReplyDelete
  151. This comment has been removed by a blog administrator.

    ReplyDelete
  152. This comment has been removed by a blog administrator.

    ReplyDelete
  153. This comment has been removed by a blog administrator.

    ReplyDelete
  154. This comment has been removed by a blog administrator.

    ReplyDelete
  155. This comment has been removed by a blog administrator.

    ReplyDelete
  156. This comment has been removed by a blog administrator.

    ReplyDelete
  157. This comment has been removed by a blog administrator.

    ReplyDelete
  158. This comment has been removed by a blog administrator.

    ReplyDelete
  159. This comment has been removed by a blog administrator.

    ReplyDelete
  160. This comment has been removed by a blog administrator.

    ReplyDelete
  161. Thank you Kamal! Great explanation and example :)

    ReplyDelete
  162. it is very use ful me

    thanks you

    ReplyDelete
  163. http://www.javaproficiency.com/2015/11/how-to-sort-treeset-with-user-defined.html

    ReplyDelete
  164. Hi,
    I understand the code wise approach but i have a doubt, you showed the Comparator also can sort by ID , then Why should we go for Comparable when we can achieve the same thing in the Comparator??

    ReplyDelete
  165. First of all i would like to say thanks for the wonderful explanation, I have a Doubt that you have showed that Comparator can do the work which Comparable can do(Ex: Your ID sort example can achievable in both), then Why we should go for Comparable when Comparator can do the same work? Why we use Comparable when all the things available in Comparator??

    Thank You.

    ReplyDelete
  166. Very clear and useful, thank you.

    ReplyDelete
  167. This comment has been removed by a blog administrator.

    ReplyDelete
  168. Excellent Blog on Comparable and Comparator

    ReplyDelete
  169. This comment has been removed by a blog administrator.

    ReplyDelete
  170. This comment has been removed by a blog administrator.

    ReplyDelete
  171. This comment has been removed by a blog administrator.

    ReplyDelete
  172. This comment has been removed by a blog administrator.

    ReplyDelete
  173. This comment has been removed by a blog administrator.

    ReplyDelete
  174. @Naveen Shriyan - Comparable is used to compare the object itself with others, but there can be only one way of comparing when we use Camparable. However, if we need to compare the objects in different ways, the Comparator is required. For example, let's say we need to compare Employee objects based on different attributes on different scenarios; by empId at some scenarios, but by name at other scenarios. This results in the requirement of Comparator.

    ReplyDelete
  175. This comment has been removed by a blog administrator.

    ReplyDelete
  176. This comment has been removed by a blog administrator.

    ReplyDelete

Post a Comment

We appreciate your opinions, suggestions and criticism.

Creative Commons License Digizol by Kamal Mettananda is licensed under a Creative Commons Attribution-Noncommercial-No Derivative Works 3.0 License .
URL of this page must be supplied in attribution
© 2004-2017