Showing posts with label Comparable. Show all posts
Showing posts with label Comparable. Show all posts

Difference between Comparator and Comparable interface in Java


Comparator and Comparable are two interfaces which used to implement Object sorting in Java. It used to sort Objects stored in any Collection classes like HashMap, HashTable, ArrayList etc., Whenever we implement Comparator interface then we need to implement compare (Object o1, Object o2) method and compareTo(Object o) method for Comparable interface. 
Going further we will discuss on differene between these 2 interface and lets see small example on how to use Comparator and Comprable interfaces. 

Difference:

  • Comparator interface used to compare any class Objects by compare (Object o1, Object o2) method, whereas Comparable interface to sort same class Objects by compareTo(Object o) method. 
  • Comparator defined in java.util package which says to use it as utility to sort Objects, while Comparable interface defined in java.lang package.
  • Comparable interface used to implement natural ordering of Object which used in Date, String and Wrapper classes in Java. If its a same class Objects then compareTo(Onject o) is a good practice to use it. 
  • Collections.sort(List) here objects will be sorted on the basis of CompareTo method in Comparable. Collections.sort(List, Comparator) here objects will be sorted on the basis of Compare method in Comparator.

Comparator Example:


import java.util.Comparator;

class Employee implements Comparator<Employee>{
 
 private String name;
 private int id;
 
 public Employee() {
 }
 
 public String getName() {
  return name;
 }
 public int getId() {
  return id;
 }
 public Employee(String name,int id){
  this.id=id;
  this.name=name;
 }
 
 // Sorting based on Employee Name
 @Override
 public int compare(Employee obj1, Employee obj2) {
     if(obj1.name.toString().compareTo(obj2.name.toString())>0){
      return 1;
     }else if(obj1.name.toString().compareTo(obj2.name.toString())<0){
      return -1;
     }else 
      return 0;     
 }
 
 // Sorting based on Employee Id
 /*@Override
 public int compare(Employee obj1, Employee obj2) {
  return obj1.id - obj2.id; 
 }*/
}



import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class ComparatorTest  {

 public static void main(String[] args) {
  
  List <Employee>list = new ArrayList<Employee>();
  
  Employee e1 = new Employee("Raj",22);
  Employee e2 = new Employee("Anna",25);
  Employee e3 = new Employee("David",12);
  Employee e4 = new Employee("Steve",100);
  Employee e5 = new Employee("Jobs",220);
  Employee e6 = new Employee("Bond",13);
  
  list.add(e1);
  list.add(e2);
  list.add(e3);
  list.add(e4);
  list.add(e5);
  list.add(e6);
  
  Collections.sort(list, new Employee());
  
                   for (Employee contact : list) {
   System.out.println(contact.getName());
  }
 }
}


OUTPUT:


Anna
Bond
David
Jobs
Raj
Steve



Comparable Example:


public class Employee implements Comparable<Employee> {

 private String empId;
 private String empName;

 public Employee() {
 }
 
 public Employee(String empId, String empName){
  this.empId = empId;
  this.empName = empName;
 }
 
 public String getEmpId() {
  return empId;
 }
 
 public String getEmpName() {
  return empName;
 }

 @Override
 public int compareTo(Employee emp) {
  return this.empName.compareTo(emp.empName);
 }
}



import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

public class CompratorTest {
 public static void main(String[] args) {
  
  List<Employee> arr = new ArrayList<Employee>();
  
  arr.add(new Employee("22","Raj"));
  arr.add(new Employee("25","Anna"));
  arr.add(new Employee("12","David"));
  arr.add(new Employee("100","Steve"));
  arr.add(new Employee("220","Jobs"));
  arr.add(new Employee("13","Bond"));
  
  //Object sort using Comparable
  Collections.sort(arr);

  Iterator<Employee> itr1 = arr.iterator();
  
  while (itr1.hasNext()) {
   Employee empobj = (Employee) itr1.next();
   System.out.println(empobj.getEmpName()+" \t\t "+empobj.getEmpId());
  }
 }
}


OUTPUT:


Anna    25
Bond    13
David    12
Jobs    220
Raj    22
Steve    100

Object sorting using Comparator and Comparable Interface in Java

Today we will discuss about how to sort Object using Comparator and Comparable interface in Java. 

       How to sort Object using Comparator and Comparable Interface in Java is a frequent question in most of the Core Java interview questions. It can be just theory question or even some interviewer may ask to write sample code for both. In that case one has to be prepared for both to explain the different and importance of both Interface in Java and also to write a sample code. 

       Lets see some important different between these two Interface's in Java. 

  • Comparator Interface is from java.util package and Comparable Interface is from java.lang package.
  • For using Comparator Interface we need to import java.util.Comparator, where as Comparable is by default. 
  • If we implement Comparator Interface then we need to implement method called public int compare(Object obj1, Object obj2) and for Comparable Interface we need to implement method called public int compareTo(Objectobj)
  • If we see Comparator Interface it will be used to Compare 2 objects different Objects of a class and where Comparable Interface will be used to Compare same class local member variables with the Object provided to CompareTo method. 

          
     Example:

       Below example Employee Class which will implement both Comparator and Comparable Interface and also has the method implementation for compare() and compareTo() methods. 
       compare() method has 2 input parameters of Employee class object and used to sort based on Employee Name (empName). 
       comapreTo() method has single Employee class object and sorted based Employee Address (empAddress)     


Employee.java

public class Employee implements Comparator<Employee>, Comparable<Employee> {

 private String empName;
 private String empAddress;

 public Employee() {
 }

 public Employee(String empName, String empAddress) {
  this.empAddress = empAddress;
  this.empName = empName;
 }

 public String getEmpName() {
  return empName;
 }

 public void setEmpName(String empName) {
  this.empName = empName;
 }

 public String getEmpAddress() {
  return empAddress;
 }

 public void setEmpAddress(String empAddress) {
  this.empAddress = empAddress;
 }

 public int compare(Employee o1, Employee o2) {
  String o1Name = o1.getEmpName();
  String o2Name = o2.getEmpName();
  if (o1Name.compareTo(o2Name) > 0) {
   return 1;
  } else if (o1Name.compareTo(o2Name) < 0) {
   return -1;
  } else {
   return 0;
  }
 }

 public int compareTo(Employee obj) {
  return this.empAddress.compareTo(obj.empAddress);
 }
}

       

CompratorComparableTest.java

public class CompratorComparableTest {
 public static void main(String[] args) {
  
  List<Employee> arr = new ArrayList<Employee>();
  arr.add(new Employee("jobs", "delhi"));
  arr.add(new Employee("mike", "bangalore"));
  arr.add(new Employee("vera", "madras"));
  arr.add(new Employee("raja", "chennai"));
  arr.add(new Employee("mani", "rorkee"));
  arr.add(new Employee("khan", "mumbai"));
  
  // Object sort using comprator
  Collections.sort(arr, new Employee());  
  Iterator<Employee> itr = arr.iterator();
  System.out.println("Object sort using comparator - sort by Name");
  while (itr.hasNext()) {
   Employee emp = (Employee) itr.next();
   System.out.println(emp.getEmpName()+" \t\t "+emp.getEmpAddress());
  }
  
  System.out.println("\n\n");
  
  //Object sort using comprable
  Collections.sort(arr);
  Iterator<Employee> itr1 = arr.iterator();
  System.out.println("Object sort using comprable - sort by Address");
  while (itr1.hasNext()) {
   Employee empobj = (Employee) itr1.next();
   System.out.println(empobj.getEmpName()+" \t\t "+empobj.getEmpAddress());
  }
 }
}




OUTPUT:


Object sort using comparator - sort by Name
jobs    delhi
khan    mumbai
mani    rorkee
mike    bangalore
raja    chennai
vera    madras



Object sort using comprable - sort by Address
mike    bangalore
raja    chennai
jobs    delhi
vera    madras
khan    mumbai
mani    rorkee


Hope you are clear on using Comparator and Comparable Interface in Java. Please drop your comments.