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 besorted 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.
- positive – this object is greater than o1
- zero – this object equals to o1
- 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.
- positive – o1 is greater than o2
- zero – o1 equals to o2
- 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 classdoes 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.- Sort employees using name, age, empId in this order (ie: when names are equal, try age and then next empId)
- 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.
Kamal Mettananada is a software engineer, Java explorer & author of Digizol, blog with computer related articles, tutorials, tips and many other information.
146 Comments for "Java Sorting: Comparator vs Comparable Tutorial"
When dealing with comparable and comparator NPE is near far.
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.
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 }
byNameLength = { a, b -> a.name.size() <=> b.name.size() } as Comparator
pretty employees.sort(byNameLength)
cheers
Nimch
Thank you very much
I'm a undergraduate student learning Java and this helped me set some things I didn't understand straight.
Thanks !
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
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>{
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.
Solution : compare Strings !
return String.valueOf(o1.getEmpId()).compareTo(String.valueOf(o2.getEmpId()));
negative – o1 is less than o1
should be
negative – o1 is less than o2
Your examples were very concise and clear. They helped me actually implement Comparator as opposed to just understanding the theory.
appreciate ur effort !
thank you!
Thank You very much.
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
Don
and please give the why we have to override hashcode() method.
Thank you and keep the tutorials coming!
-Omaha, Nebraska (USA)
A well written tutorial, thanks again!
Allasso
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);
}
Hi fan,
You will not need to convert int values to Strings in this example as Java5 does auto-boxing.
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
Thanks From Paris (France).
thanks from Brazil!
Prabhat
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
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
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);
}
Can u plz tell me why equals() and compare()methods must be consistence??
Regards,
Bibhakar.
The Comparator interface belongs to java.util.Hence please correct the article as java.util.Comparator.I think it is a typo.
There is a typo
java.lang.Comparator,
instead
java.util.Comparator
Thanks for pointing the typo in package name of java.util.Comparator interface. Now it is corrected.
Thanks
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));
}
}
Really Superb Explaination..
i searchd in many websites...i didnt seen this type of good explaination..
thank u very much
All izz well('=')
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);
}
}
}
thanks
Velu
regards gaurav g.
The desired order cann be 60,120,180...
How can i use comparator in my application..
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
Anil
Keep posting more articles.!
Thanks
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)
Question:How can you remove duplicate element from string?
Plz send me this Q's answer. My mail(mca.snayak@gmail.com)