Showing posts with label Comparator. Show all posts
Showing posts with label Comparator. 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

Using Java TreeMap

 
Today we will see about one of the important interface in Java called Map interface. Map interface and derived classes are in java.util.Map package and Map uses simple data structure that contains Key and Value. Always key must be unique Object and its uses Hashing to identify the correct Key and corresponding Value in the Sequential array (Used to call as bucket). 

Under Map interface lot of derived classes and lets see TreeMap in this tutorial.

TreeMap:
       TreeMap is an important class which implements the Map interface. As same as HashMap TreeMap also uses the Key/ Value to store the data in a sorted order. TreeMap can be created in 2 ways as natural sorted order or custom sorted order by using Comparator. Below we will see small examples for all these types.


Example: TreeMap using natural sort.


public class TreeMapTest {
 public static void main(String[] args) {
  TreeMap<String, String> map = new TreeMap<String, String>();
  map.put("4", "Delhi");
  map.put("3", "Mumbai");
  map.put("5", "Chennai");
  map.put("1", "Culcutta");
  map.put("2", "Bangalore");
  
  // Sorted TreeMap
  System.out.println("Sorted TreeMap values....");
  for (Map.Entry<String, String> entry : map.entrySet()) {
   System.out.println("KEY : "+entry.getKey() +" - VALUE : "+entry.getValue());
  }
  
  // Getting size TreeMap
  System.out.println("\nSize of TreeMap :: "+map.size());
  
  // Contains Key in TreeMap
  System.out.println("\nKey Contains (15) : "+map.containsKey("15"));
  System.out.println("Key Contains (4) : "+map.containsKey("4"));
    
  // Contains Value in TreeMap
  System.out.println("\nValue Contains (Delhi) : "+map.containsValue("Delhi"));
  System.out.println("Value Contains (Ney York) : "+map.containsValue("New York"));
    
  // Getting Reversing TreeMap
  NavigableMap<String, String> revMap = map.descendingMap();
  System.out.println("\nReverse TreeMap values....");
  for (Map.Entry<String, String> entry : revMap.entrySet()) {
   System.out.println("KEY : "+entry.getKey() +" - VALUE : "+entry.getValue());
  }
  
  // Get sub portion of map to subMap
  SortedMap<String, String> subMap = map.subMap("2","4");
  System.out.println("\nSub portion TreeMap values....");
  for (Map.Entry<String, String> entry : subMap.entrySet()) {
   System.out.println("KEY : "+entry.getKey() +" - VALUE : "+entry.getValue());
  }
  
  // Getting first Key and Entry in TreeMap
  System.out.println("\nFirst Key in TreeMap : "+map.firstKey());
  System.out.println("First Entry in TreeMap : "+map.firstEntry());
  
  // Getting last Key and Entry in TreeMap
  System.out.println("\nLast Key in TreeMap : "+map.lastKey());
  System.out.println("Last Entry in TreeMap : "+map.lastEntry());
  
  // Removing data from TreeMap
  map.remove("3");
  System.out.println("\nTreeMap size after removing 1 element : "+map.size());
  
  // Checking TreeMap is empty or not
  System.out.println("\nTreeMap empty or not : "+map.isEmpty());
  
  // Clearing complete TreeMap
  map.clear();
  System.out.println("\nTreeMap size after clearing all values : "+map.size());
  System.out.println("TreeMap empty or not : "+map.isEmpty());
  
 }
}



OUTPUT:


Sorted TreeMap values....
KEY : 1 - VALUE : Culcutta
KEY : 2 - VALUE : Bangalore
KEY : 3 - VALUE : Mumbai
KEY : 4 - VALUE : Delhi
KEY : 5 - VALUE : Chennai

Size of TreeMap :: 5

Key Contains (15) : false
Key Contains (4) : true

Value Contains (Delhi) : true
Value Contains (Ney York) : false

Reverse TreeMap values....
KEY : 5 - VALUE : Chennai
KEY : 4 - VALUE : Delhi
KEY : 3 - VALUE : Mumbai
KEY : 2 - VALUE : Bangalore
KEY : 1 - VALUE : Culcutta

Sub portion TreeMap values....
KEY : 2 - VALUE : Bangalore
KEY : 3 - VALUE : Mumbai

First Key in TreeMap : 1
First Entry in TreeMap : 1=Culcutta

Last Key in TreeMap : 5
Last Entry in TreeMap : 5=Chennai

TreeMap size after removing 1 element : 4

TreeMap empty or not : false

TreeMap size after clearing all values : 0
TreeMap empty or not : true



In above example we can see automatically TreeMap sorted and also other methods in TreeMap class.

Next we will see simple example using custom sorting using Comparator.

Example: TreeMap using custom sort - Comparator.




public class TreeMapUsingCustomComparator {
 
 public static void main(String a[]){
  TreeMap<Worker,String> map = new TreeMap<Worker, String>(new MyNameComp());
  map.put(new Worker("david",5000), "david");
  map.put(new Worker("joy",2000), "joy");
  map.put(new Worker("abel",7000), "abel");
  map.put(new Worker("ruby",9000), "ruby");
  
  for (Map.Entry<Worker, String> entry : map.entrySet()) {
   System.out.println("KEY : "+ entry.getKey() +" \t VALUE : "+entry.getValue());
  }
 }
}




public class Worker{
    
    private String name;
    private int salary;
    
    public Worker(String name, int salary){
        this.name = name;
        this.salary = salary;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getSalary() {
        return salary;
    }
    public void setSalary(int salary) {
        this.salary = salary;
    }
    public String toString(){
        return "("+this.name+":"+this.salary+")";
    }
}




public class MyNameComp implements Comparator<Worker>{
    public int compare(Worker obj1, Worker obj2) {
        return obj1.getName().compareTo(obj2.getName());
    }
}



OUTPUT: 


KEY : (abel:7000)   VALUE : abel
KEY : (david:5000)   VALUE : david
KEY : (joy:2000)   VALUE : joy
KEY : (ruby:9000)   VALUE : ruby





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.