Differences between Comparable and Comparator - sorting list by implementing Comparable and Comparator in classes and inner classes in java


In this Collection framework tutorial we will learn what are differences between java.lang.Comparable and java.util.Comparator with lots of examples and programs in java.



Contents of page :
  • What is java.lang.Comparable and java.util.Comparator in java ?
  • What are Difference between java.lang.Comparable and java.util.Comparator in java
  • Algorithm used by Comparator for sorting in java >

  • Comparable and Comparator example and programs >
  • Example/Program 1 to sort Employee list on basis of name in ascending order by implementing Comparable interface and overriding its compareTo method in java
  • Example/Program 2 to sort Employee list on basis of name in descending order by implementing Comparable interface and overriding its compareTo method in java
  • Example/Program 3 to sort Employee list on basis of name in ascending order by implementing Comparator interface and overriding its compare method in java
  • Example/Program 4 to sort Employee list on basis of name in descending order by implementing Comparator interface and overriding its compare method in java
  • Example/Program 5 to sort Employee list on basis of name and id in ascending order by implementing Comparator interface and overriding its compare method in java
  • Example/Program 6 to sort Employee list on basis of name and id in ascending order by implementing Comparator interface in inner and static nested class and overriding its compare method in java


What is java.lang.Comparable and java.util.Comparator in java?
Comparable and Comparator are used for sorting classes. But it's important to spot difference between them.  In this post I will explain you difference between them by writing programs in java.


What are difference between java.lang.Comparable and java.util.Comparator in java

Property
java.lang.Comparable
java.util.Comparator
1
Comparing instances of class
Comparable is used to compare instances of same class in java.
Comparator can be used to compare instances of same or different classes in java.
2
sorting order
Comparable can be implemented by class which need to define a natural ordering for its objects.
Example - String, Integer, Long , Date and all other wrapper classes implements Comparable.
Comparator is implemented when one wants a different sorting order and define custom way of comparing two instances.
3
Changes to class
For using Comparable, original Class must implement it.




Example of Comparable in java-

class Employee implements Comparable<Employee>



For using Comparable, Employee Class must implement it, no other class can implement it.

As used in Program 1
Class itself can implement Comparator
or
any other class can implement Comparator. Hence avoiding modification to original class.

Example of Comparator in java-

class ComparatorName implements Comparator<Employee>

class ComparatorId implements Comparator<Employee>

In above example modifications were made to ComparatorName and ComparatorId. Hence avoiding modification to Employee class.

As used in Program 4
4
Sorting on basis on one or many criteria in java
Provides sorting only on one criteria, because Comparable can be implemented by original class only in java.

We can use Comparator to sort class on many criterias because class itself or any other class can implement Comparator in java.
5
Method
After implementing Comparable class must override compareTo method

@Override
public int compareTo(Employee obj) {
//sort Employee on basis of name(ascending order)
 return this.name.compareTo(obj.name);
}


Method compares this with obj object and returns a integer.

  • positive – this is greater than obj
  • zero – this is equal to obj
  • negative – this is less than obj






As used in Program 1
After implementing Comparable class must override compare method

@Override
public int compare(Employee obj1, Employee obj2) {
//sort Employee on basis of name(ascending order)
   return obj1.name.compareTo(obj2.name);
}
  

Method compares obj1 with obj2 object and returns a integer.

  • positive – obj1 is greater than obj2
  • zero – obj1 is equal to obj2
  • negative – obj1 is less than obj2






As used in Program 3
6
Package
java.lang

java.lang package is automatically imported by every program in java.

Hence, we need not to write explicit statement for importing java.lang.Comparable.
java.util

We need to write explicit import statement -

import java.util.Comparator
7
Using Collections.sort
Let's say we wanna sort list of Employee,
Collections.sort(list) uses Comparable interface for sorting class.

As used in Program 1
Let's say we wanna sort list of Employee,
Collections.sort(list,new ComparatorName());
uses Comparator interface for sorting class.

As used in Program 5



Algorithm used by Comparator for sorting in java >
Implement Comparator interface and override its compare method in java.
Call Collections.sort and pass list [i.e. list] as parameter.
Collections.sort internally calls Arrays.sort,
Arrays.Sort() internally calls Merge Sort.
Merge sort calls overridden compare method of Comparator interface for comparison of values.

Must know fact :
If number of elements is less than 7 then Insertion Sort is used rather than Merge Sort. (because in case elements are less than 7 it offers better time complexity)



Comparable and Comparator example and programs in java>

Example/ Program 1 to sort Employee list on basis of name in ascending order by implementing Comparable interface and overriding its compareTo method in java
import java.util.ArrayList;
import java.util.Collections;
class Employee implements Comparable<Employee>{
   String name;
   String id;
   public Employee(String name, String id) {
       this.name = name;
       this.id = id;
   }
  
   @Override
   public int compareTo(Employee otherEmployee) {
      //sort Employee on basis of name(ascending order)
      return this.name.compareTo(otherEmployee.name);
   }
   // toString() method overrides Object class’s toString() method.
   // toString() method is used to give a string representation of an object.
   @Override
   public String toString() {
       return "Employee{" + "name=" + name + ", id=" + id  + '}';
   }
}
/**
* @author AnkitMittal
* Copyright (c), AnkitMittal JavaMadeSoEasy.com
* Main class
*/
public class ComparableUsageExample {
   public static void main(String[] args) {
       Employee emp1=new Employee("sam","4");
       Employee emp2=new Employee("amy","2");
       Employee emp3=new Employee("brad","1");

       ArrayList<Employee> list=new ArrayList<Employee>();
       list.add(emp1);
       list.add(emp2);
       list.add(emp3);
     
       System.out.println("list Before sorting : \n"+list);
       Collections.sort(list);
       System.out.println("\nlist after sorting on basis of name(ascending order) : \n"+list);
      
   }
}
/*OUTPUT
list Before sorting :
[Employee{name=sam, id=4}, Employee{name=amy, id=2}, Employee{name=brad, id=1}]
list after sorting on basis of name(ascending order) :
[Employee{name=amy, id=2}, Employee{name=brad, id=1}, Employee{name=sam, id=4}]
*/




Example/Program 2 to sort Employee list on basis of name in descending order by implementing Comparable interface and overriding its compareTo method in java
In the above program replace compareTo method of Employee class with below compareTo method.
      @Override
   public int compareTo(Employee otherEmployee) {
          // sort Employee on basis of name(descending order)
          return otherEmployee.name.compareTo(this.name);
   }

OUTPUT will be >
/*OUTPUT
list Before sorting :
[Employee{name=sam, id=4}, Employee{name=amy, id=2}, Employee{name=brad, id=1}]
list after sorting on basis of name(descending order) :
[Employee{name=sam, id=4}, Employee{name=brad, id=1}, Employee{name=amy, id=2}]
*/



Example/Program 3 to sort Employee list on basis of name in ascending order by implementing Comparator interface and overriding its compare method in java
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
class Employee implements Comparator<Employee>{
   String name;
   String id;
  
   public Employee() {}
  
   public Employee(String name, String id) {
       this.name = name;
       this.id = id;
   }
  
   @Override
   public int compare(Employee obj1, Employee obj2) {
      //sort Employee on basis of name(ascending order)
      return obj1.name.compareTo(obj2.name);
   }
  
   @Override
   public String toString() {
       return "Employee{" + "name=" + name + ", id=" + id  + '}';
   }
  
  
}
/**
* @author AnkitMittal
* Copyright (c), AnkitMittal JavaMadeSoEasy.com
* Main class
*/
public class ComparatorUsageExample {
   public static void main(String[] args) {
       Employee emp1=new Employee("sam","4");
       Employee emp2=new Employee("amy","2");
       Employee emp3=new Employee("brad","1");

       ArrayList<Employee> list=new ArrayList<Employee>();
       list.add(emp1);
       list.add(emp2);
       list.add(emp3);
     
       System.out.println("list Before sorting : \n"+list);
       Collections.sort(list,new Employee());
       System.out.println("\nlist after sorting on basis of name(ascending order) : \n"+list);
      
   }
}
/*OUTPUT
list Before sorting :
[Employee{name=sam, id=4}, Employee{name=amy, id=2}, Employee{name=brad, id=1}]
list after sorting on basis of name(ascending order) :
[Employee{name=amy, id=2}, Employee{name=brad, id=1}, Employee{name=sam, id=4}]
*/




Example/ Program 4 to sort Employee list on basis of name in descending order by implementing Comparator interface and overriding its compare method in java
In the above program replace compare method of Employee class with below compare method in java.
      @Override
   public int compare(Employee obj1, Employee obj2) {
          // sort Employee on basis of name(descending order)
          return obj2.name.compareTo(obj1.name);
   }

OUTPUT of above will be >
/*OUTPUT
list Before sorting :
[Employee{name=sam, id=4}, Employee{name=amy, id=2}, Employee{name=brad, id=1}]
list after sorting on basis of name(descending order) :
[Employee{name=sam, id=4}, Employee{name=brad, id=1}, Employee{name=amy, id=2}]
*/


Example/ Program 5 to sort Employee list on basis of name and id in ascending order by implementing Comparator interface and overriding its compare method in java
ComparatorName and ComparatorId are two classes which will implement Comparator to provide sorting on basis of name and id respectively in java.
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
class Employee{
   String name;
   String id;
  
   public Employee() {}
  
   public Employee(String name, String id) {
       this.name = name;
       this.id = id;
   }
  
  
   @Override
   public String toString() {
       return "Employee{" + "name=" + name + ", id=" + id  + '}';
   }
  
}
class ComparatorName implements Comparator<Employee>{
   @Override
   public int compare(Employee obj1, Employee obj2) {
      //sort Employee on basis of name(ascending order)
      return obj1.name.compareTo(obj2.name);
   }
  
}
class ComparatorId implements Comparator<Employee>{
   @Override
   public int compare(Employee obj1, Employee obj2) {
      //sort Employee on basis of id(ascending order)
      return obj1.id.compareTo(obj2.id);
   }
  
}
/**
* @author AnkitMittal
* Copyright (c), AnkitMittal JavaMadeSoEasy.com
* Main class
*/
public class ComparatorUsageExample {
   public static void main(String[] args) {
       Employee emp1=new Employee("sam","4");
       Employee emp2=new Employee("amy","2");
       Employee emp3=new Employee("brad","1");

       ArrayList<Employee> list=new ArrayList<Employee>();
       list.add(emp1);
       list.add(emp2);
       list.add(emp3);
     
       System.out.println("list Before sorting : \n"+list);
       Collections.sort(list,new ComparatorName());
       System.out.println("\nlist after sorting on basis of name(ascending order) : \n"+list);
       Collections.sort(list,new ComparatorId());
       System.out.println("\nlist after sorting on basis of id(ascending order) : \n"+list);
      
   }
}
/*OUTPUT
list Before sorting :
[Employee{name=sam, id=4}, Employee{name=amy, id=2}, Employee{name=brad, id=1}]
list after sorting on basis of name(ascending order) :
[Employee{name=amy, id=2}, Employee{name=brad, id=1}, Employee{name=sam, id=4}]
list after sorting on basis of id(ascending order) :
[Employee{name=brad, id=1}, Employee{name=amy, id=2}, Employee{name=sam, id=4}]
*/




Example/Program 6 to sort Employee list on basis of name and id in ascending order by implementing Comparator interface in inner and static nested class and overriding its compare method in java
ComparatorName (inner class of Employee class) and ComparatorId (static nested class of Employee class) are two classes which will implement Comparator to provide sorting on basis of name and id respectively.

How to use inner and static nested class in java?
For accessing inner class we need to create instance of top level class and then instance of inner class.
For accessing static nested class we need not to create instance of top level class, we need to have instance of static nested class only.

new Employee().new ComparatorName()  >using inner class
new Employee  .    ComparatorId()    >using static nested class

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
class Employee{
   String name;
   String id;
  
   public Employee() {}
  
   public Employee(String name, String id) {
       this.name = name;
       this.id = id;
   }
  
  
   @Override
   public String toString() {
       return "Employee{" + "name=" + name + ", id=" + id  + '}';
   }
   //Inner class
   class ComparatorName  implements Comparator<Employee>{
      @Override
       public int compare(Employee obj1, Employee obj2) {
          //sort Employee on basis of name(ascending order)
          return obj1.name.compareTo(obj2.name);
       }
   }
  
   //static nested class
   static class ComparatorId  implements Comparator<Employee>{
      @Override
       public int compare(Employee obj1, Employee obj2) {
          //sort Employee on basis of id(ascending order)
          return obj1.id.compareTo(obj2.id);
       }
   }
}
/**
* @author AnkitMittal
* Copyright (c), AnkitMittal JavaMadeSoEasy.com
* Main class
*/
public class ComparatorUsageExample {
   public static void main(String[] args) {
       Employee emp1=new Employee("sam","4");
       Employee emp2=new Employee("amy","2");
       Employee emp3=new Employee("brad","1");

       ArrayList<Employee> list=new ArrayList<Employee>();
       list.add(emp1);
       list.add(emp2);
       list.add(emp3);
     
       System.out.println("list Before sorting : \n"+list);
       Collections.sort(list,new Employee().new ComparatorName());
       System.out.println("\nlist after sorting on basis of name(ascending order), "
                 + "using inner class : \n"+ list);
       Collections.sort(list,new Employee.ComparatorId());
       System.out.println("\nlist after sorting on basis of id(ascending order), "
                 + "using static nested class : \n"+list);
      
   }
}
/*OUTPUT
list Before sorting :
[Employee{name=sam, id=4}, Employee{name=amy, id=2}, Employee{name=brad, id=1}]
list after sorting on basis of name(ascending order), using inner class :
[Employee{name=amy, id=2}, Employee{name=brad, id=1}, Employee{name=sam, id=4}]
list after sorting on basis of id(ascending order), using static nested class :
[Employee{name=brad, id=1}, Employee{name=amy, id=2}, Employee{name=sam, id=4}]
*/


So in this Collection framework tutorial we learned what are differences between java.lang.Comparable and java.util.Comparator with lots of examples and programs in java.



Having any doubt? or you you liked the tutorial! Please comment in below section.
Please express your love by liking JavaMadeSoEasy.com (JMSE) on facebook, following on google+ or Twitter.


RELATED LINKS>

Collection in java



Sorting Collection by implementing comparator and Comparable, using TreeMap and TreeSet, Collections.sort and Arrays.sort >

Arrays.sort to sort arrays by implementing Comparator and how Comparator of superclass can be used by subclasses in java


Sort Set by using TreeSet and by implementing Comparator and Comparable interface in java


Sort Map by key in Ascending and descending order by implementing Comparator interface and overriding its compare method and using TreeMap in java


Sort Map by value in Ascending and descending order by implementing Comparator interface and overriding its compare method in java





No comments:

Post a Comment