Java News Tips Software
Java News Tips Software | Contact | Facebook | Twitter RSS

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

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.

Labels: , ,


173 Comments

  1. You should also try to handle null values.

    When dealing with comparable and comparator NPE is near far.
  2. 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.
  3. 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 }
  4. 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)
  5. Anonymous Anonymous on August 13, 2008 4:20 PM  
    this is good just what I looked for.

    cheers
    Nimch
  6. Anonymous Anonymous on November 01, 2008 3:32 AM  
    The context in which comparable or comparator should be used is pretty clear, good tutorial
  7. Anonymous Anonymous on November 10, 2008 5:29 AM  
    Exactly what I was looking for to get ready for exam
    Thank you very much
  8. Anonymous Anonymous on November 30, 2008 6:39 PM  
    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 !
  9. Nice one. Very helpful...
  10. Anonymous Anonymous on December 19, 2008 3:34 AM  
    This is very helpful.
  11. Anonymous Anonymous on January 21, 2009 9:04 PM  
    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
  12. Anonymous Anonymous on January 23, 2009 5:39 PM  
    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.
  13. Anonymous Anonymous on February 12, 2009 7:32 PM  
    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()));
  14. Anonymous Anonymous on February 19, 2009 6:28 PM  
    Real good thanks! Im getting ready for exam and this was so much clearer than the PDF we was handen. Cheers
  15. Anonymous Anonymous on February 25, 2009 8:55 PM  
    Typo above:
    negative – o1 is less than o1

    should be
    negative – o1 is less than o2
  16. 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.
  17. Anonymous Anonymous on March 21, 2009 8:33 PM  
    Thanks, Really a good tutorial.
  18. Anonymous Anonymous on April 06, 2009 5:48 AM  
    Thanks, Its really good artical to understand and well explained.
  19. Anonymous Anonymous on April 29, 2009 5:31 PM  
    it was very usefull....thanks a lot
  20. Good one was very useful!

    appreciate ur effort !
  21. Anonymous Anonymous on June 03, 2009 12:15 AM  
    very nice!
    thank you!
  22. Anonymous Anonymous on June 04, 2009 8:57 PM  
    very nice and clean!
    Thank You very much.
  23. Anonymous Anonymous on June 26, 2009 2:03 PM  
    it very clear thank u very much
  24. Anonymous Anonymous on July 04, 2009 4:42 PM  
    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
  25. Anonymous Anonymous on July 04, 2009 6:32 PM  
    this really helped
  26. Nice one !!! It would be helpful to everyone
  27. Anonymous Anonymous on July 16, 2009 5:13 PM  
    This was the best article. Very, very helpful, nice and clean.
  28. Anonymous Anonymous on July 20, 2009 9:00 PM  
    Excellent explanation, thanks much.

    Don
  29. Anonymous Anonymous on July 21, 2009 10:41 PM  
    easy, concise, simple and an accurate example. Thanks Kamal
  30. Anonymous Anonymous on July 26, 2009 7:42 AM  
    He has written a very good article . Instead of pointing out mistakes , appreciate his efforts & provide better suggestions. Great Job
  31. Thanks a lot. Very useful tutorial. Vladimir
  32. Very nice,easily understandable,
    and please give the why we have to override hashcode() method.
  33. To the point and precise. Great work!!
  34. 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!
  35. 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;
  36. Anonymous Anonymous on October 18, 2009 4:57 AM  
    thanks for a clean tutorial. I get it now !

    -Omaha, Nebraska (USA)
  37. Anonymous Jijo Mathew on October 25, 2009 5:08 PM  
    Is there any way to include more than one method in a single class, rather than creating single compare method in one class
  38. nice explaination! Just one correction - Comparator interface is under java.util package and not under java.lang
  39. 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!
  40. Anonymous Anonymous on December 10, 2009 4:06 PM  
    Good example............. Yeah I got the point.. Thank you very much :) cheers
  41. really nice explanation.. hats off
  42. good article! thanks!
  43. veeeeeeeeeeerrrrrry helpful, thorough, and well written, thanks.

    Allasso
  44. 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);
    }
  45. // 42
    Hi fan,

    You will not need to convert int values to Strings in this example as Java5 does auto-boxing.
  46. Anonymous Anonymous on February 03, 2010 1:25 AM  
    The explanation is super. thanks.
  47. This really helped in my preparation about Comparable and Comparator. Well framed I book marked.
  48. 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
  49. Thank you for taking the time to publish this, it was very clear. The best basic tutorial on comparator I have seen!
  50. Anonymous Anonymous on March 01, 2010 3:41 PM  
    Thank you so much ! I found what I was looking for !!
    Thanks From Paris (France).
  51. Anonymous Anonymous on March 24, 2010 3:28 AM  
    Your post help me a lot.
    thanks from Brazil!
  52. Anonymous Anonymous on March 30, 2010 11:02 PM  
    thank you . I from vietnamese
  53. Anonymous Anonymous on April 12, 2010 3:57 PM  
    Thank you....Very clearly explained
  54. Anonymous Anonymous on April 14, 2010 6:32 PM  
    Good information in precise form
  55. Thanks, it helped me.
  56. Anonymous Anonymous on April 30, 2010 10:00 AM  
    Simply simple in simple terms... the basic context of both interfaces is clear
  57. hi
  58. Anonymous Anonymous on May 25, 2010 6:10 PM  
    thax a lot dude...very useful tutorial....thanx again

    Prabhat
  59. Anonymous Anonymous on May 31, 2010 8:42 PM  
    very nice... and helpful. thks biju
  60. Anonymous Anonymous on June 01, 2010 8:08 PM  
    hi can u plz tell me why equals() and compare()methods must be consistence
  61. 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
  62. this is very helpful tutorial. really good one
  63. Anonymous Anonymous on June 09, 2010 1:28 PM  
    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
  64. Anonymous Anonymous on June 13, 2010 5:55 AM  
    Very Clear. Thank You.
  65. Anonymous Anonymous on June 17, 2010 9:33 PM  
    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);
    }
  66. Anonymous Anonymous on June 21, 2010 12:14 AM  
    very good explain nation.Really Good..Keep up the Good Work Going....
  67. I must read your other articles. Its nice article.
  68. Anonymous Anonymous on July 06, 2010 12:18 PM  
    Here,Collections are used for comparing the different instances but....for the same class. Why so??
  69. Anonymous Anonymous on July 06, 2010 12:20 PM  
    Hi,

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

    Regards,
    Bibhakar.
  70. Great, to the point post. Nice way of covering too with good examples.
  71. Anonymous Anonymous on August 06, 2010 10:25 PM  
    Hi,

    The Comparator interface belongs to java.util.Hence please correct the article as java.util.Comparator.I think it is a typo.
  72. Anonymous Anonymous on August 13, 2010 4:40 PM  
    This is excellence tutorial for beginners to understand the d/f b/w comparable and comparator...Excellent job
  73. This is really great tutorial with nice example. Thanx a lot
  74. wat's d difference between compare() and compareTo() methods
  75. Comparator belongs to util package.....Not to lang........
  76. Hi,
    There is a typo
    java.lang.Comparator,
    instead
    java.util.Comparator
  77. Hi all,
    Thanks for pointing the typo in package name of java.util.Comparator interface. Now it is corrected.
  78. 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.
  79. 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
  80. Very clear explanation of how comparator and comparable work with nice examples, thank you so much and keep posting more articles like this.
  81. Anonymous Anonymous on October 07, 2010 1:28 AM  
    Excellent example.. very well explained...`
  82. 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));
    }
    }
  83. Anonymous Anonymous on October 15, 2010 9:16 AM  
    really good one.. thanks a lot
  84. Anonymous Anonymous on October 24, 2010 1:35 PM  
    Thanks for this great explanation. I've always had trouble understanding the comparator mechanisms until now.
  85. Anonymous Anonymous on October 28, 2010 7:04 PM  
    ('=')
    Really Superb Explaination..
    i searchd in many websites...i didnt seen this type of good explaination..
    thank u very much
    All izz well('=')
  86. Anonymous Anonymous on November 12, 2010 9:47 PM  
    I was able to implement the same things. Thank you for this :)
  87. Thanks alot ...Very clear and easy to understand :)
  88. I implemented the same code... It works
  89. Anonymous Anonymous on November 17, 2010 3:27 PM  
    One of THE best tutorial..
  90. Nice and simple tutorial, thanks!
  91. good examples....
  92. Awesome explanation, very useful contents.
  93. Anonymous Anonymous on January 04, 2011 2:09 PM  
    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);
    }

    }

    }
  94. 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! :)
  95. Very good example..
  96. Anonymous Anonymous on January 18, 2011 5:24 AM  
    Terrific.I like the way u explained.thank u so much......
  97. Anonymous Anonymous on January 27, 2011 2:18 AM  
    thanks a lot for this tutorial. it was very helpful
  98. Anonymous Anonymous on February 01, 2011 9:54 PM  
    Thank you very much, It was really helpful, thanks for your time
  99. Anonymous Anonymous on February 04, 2011 9:57 AM  
    This comment has been removed by a blog administrator.
  100. Nicely framed example. good job
  101. hey pls give short n simplest small prg which can be copy n implemented....
  102. Its really helpfull
  103. really good tutorial, thanks.
  104. Anonymous Anonymous on April 20, 2011 1:46 AM  
    very nice tutorial... easy to understand the content..
    thanks
    Velu
  105. 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.
  106. Anonymous Anonymous on May 25, 2011 7:03 PM  
    thanks
    regards gaurav g.
  107. Anonymous Anonymous on June 15, 2011 1:30 AM  
    Wow, thanks a lot for clearing this up, you saved me hours of time.
  108. Anonymous Sushanta Dutta on June 22, 2011 2:11 PM  
    why equals() should be override in the context of Comparator/Comparable?? please send me the details discussion.
  109. Anonymous Anonymous on July 02, 2011 6:33 PM  
    It's really Good
  110. Anonymous Anonymous on July 05, 2011 4:49 PM  
    I don't understand the consistency between compare(),compareTo(), and equals().
  111. Anonymous Anonymous on July 12, 2011 10:47 PM  
    Good article.
  112. Anonymous Anonymous on July 26, 2011 5:30 PM  
    thanks...simple bt helpful
  113. Anonymous Anonymous on July 27, 2011 6:13 AM  
    Good example, clearly explained.
  114. nice one. Able to clearly understand the concept.
  115. Anonymous Anonymous on August 20, 2011 10:17 AM  
    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..
  116. // 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
  117. Very nicely explained :):)Thanks
  118. Thank you very helpful!
  119. This really helps me a lot, thank you!!!
  120. This is a great tutorial. Thank You!
  121. Hi...This is nice blog..thank you for this information..It helped me...+1ed it.
  122. @Ravi Thanks
  123. 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
  124. Anonymous Anonymous on December 26, 2011 7:40 PM  
    nice and short tutorial, cleared all my doubts
  125. Anonymous Anonymous on December 30, 2011 2:55 AM  
    Excellent demo.
  126. great
  127. Anonymous Anonymous on April 04, 2012 3:41 PM  
    Great Job done. :)
    Keep posting more articles.!
  128. 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.
  129. 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
  130. Anonymous Anonymous on June 07, 2012 5:21 PM  
    Thanks a lot! very informative and precise! from Sri lanka :)
  131. Anonymous Anonymous on June 08, 2012 2:20 PM  
    Wonderfully You have given your Explanation.Excellent
  132. Very nice explanation. Good job...
  133. Anonymous Anonymous on June 21, 2012 10:10 AM  
    Super... lolved It..:)
  134. Anonymous Anonymous on June 23, 2012 1:46 PM  
    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.
  135. @134: Thanks a lot for your encouraging comment. Really appreciate it.
  136. 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)
  137. Really nice article..so simple yet very informative.
  138. Hi..
    Question:How can you remove duplicate element from string?
    Plz send me this Q's answer. My mail(mca.snayak@gmail.com)
  139. Anonymous Anonymous on October 09, 2012 2:38 PM  
    Thank you! Now I know the difference
  140. Anonymous Anonymous on October 22, 2012 1:02 PM  
    Thanks Nice One
  141. Anonymous Anonymous on October 24, 2012 6:15 AM  
    Thank you for your explain...
  142. Anonymous Anonymous on October 29, 2012 6:05 AM  
    thanks, your post helped me a lot.
  143. Anonymous Anonymous on November 17, 2012 2:50 AM  
    Very good article, i can say best one to understand comparable and comparator
  144. 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
  145. Anonymous Anonymous on February 07, 2013 4:46 PM  
    Thanks for this article, very easy to understand.
  146. 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.
  147. Thanks for this article, this is really very easy to understand...
  148. Thanks a lot. I was very much confused with two concepts when to use what.Amazing!!!
  149. Nice explanation.....thanks a lot
  150. Anonymous Anonymous on November 07, 2013 5:30 AM  
    This comment has been removed by a blog administrator.
  151. This comment has been removed by a blog administrator.
  152. This comment has been removed by a blog administrator.
  153. Anonymous Anonymous on December 02, 2013 2:21 AM  
    This comment has been removed by a blog administrator.
  154. Anonymous Anonymous on January 10, 2014 12:10 PM  
    This comment has been removed by a blog administrator.
  155. Anonymous Anonymous on January 10, 2014 1:28 PM  
    This comment has been removed by a blog administrator.
  156. Anonymous Anonymous on January 10, 2014 6:39 PM  
    This comment has been removed by a blog administrator.
  157. Anonymous Anonymous on January 13, 2014 1:21 PM  
    This comment has been removed by a blog administrator.
  158. Anonymous Anonymous on January 20, 2014 2:19 PM  
    This comment has been removed by a blog administrator.
  159. Anonymous Anonymous on January 21, 2014 9:14 PM  
    This comment has been removed by a blog administrator.
  160. Anonymous Anonymous on February 14, 2014 4:07 AM  
    This comment has been removed by a blog administrator.
  161. Anonymous Anonymous on February 14, 2014 5:41 AM  
    This comment has been removed by a blog administrator.
  162. Anonymous Anonymous on February 14, 2014 6:43 AM  
    This comment has been removed by a blog administrator.
  163. Anonymous Anonymous on February 14, 2014 7:18 AM  
    This comment has been removed by a blog administrator.
  164. Anonymous Anonymous on February 14, 2014 9:21 AM  
    This comment has been removed by a blog administrator.
  165. Anonymous Anonymous on February 15, 2014 6:45 AM  
    This comment has been removed by a blog administrator.
  166. Anonymous Anonymous on March 24, 2014 6:47 PM  
    This comment has been removed by a blog administrator.
  167. Anonymous Anonymous on March 28, 2014 3:09 AM  
    This comment has been removed by a blog administrator.
  168. Thank you Kamal! Great explanation and example :)
  169. Anonymous Anonymous on December 02, 2014 9:26 PM  
    it is very use ful me

    thanks you
  170. http://www.javaproficiency.com/2015/11/how-to-sort-treeset-with-user-defined.html
  171. 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??
  172. 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.
  173. Very clear and useful, thank you.
ABOUT AUTHOR
Page Views :
Email :
PREVIOUS ARTICLES
Select Month:
TOP
Free counter and web stats