Guide on Programming, Internet and Technology

DigiZol
| Contact

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

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.lang.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.lang.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().compareTo(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: , ,

Translate into your language
Reader Comments
Comments Count: 26
Write your own opinion
Share with others
E-mail
Search More Articles
  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 (August 13, 2008 4:20 PM)  
    this is good just what I looked for.

    cheers
    Nimch
  6. The context in which comparable or comparator should be used is pretty clear, good tutorial
  7. Exactly what I was looking for to get ready for exam
    Thank you very much
  8. 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. This is very helpful.
  11. 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. 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()));
  13. Real good thanks! Im getting ready for exam and this was so much clearer than the PDF we was handen. Cheers
  14. Typo above:
    negative – o1 is less than o1

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

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

Post a Comment

We appreciate your opinions, suggestions and criticism.

ABOUT AUTHOR
Kamal Mettananada is a Software Architect, Java Explorer and Blogger. Digizol consists of computer related articles, tutorials, tips and other information.
ARCHIVES
Select Month:

Free counter and web stats

FEED SUBSCRIPTION
Subscribe to our feed using your online news reader, approximately 1-2 articles per week.
ABOUT US
^top^