Saturday, January 4, 2014

Comparable v/s Comparator

Comparable and Comparator are the interfaces used for sorting the elements in the collection. To sort the data in collection either, the data object in the collection has to implement Comparble interface or an extra object to be passed as an parameter to the sort method which implemented Comparator.
Collection.sort method
public static <T extends Comparable<? super T>> void sort(List<T> list) //Using comparable 
public static <T> void sort(List<T> list, Comparator<? super T> c) //Using comparator

Example using Comparable interface

Object implemented Comparable

package com.test.collection;

public class Person implements Comparable<Person> {
   private long id;
   //Getters and Setters
   public int compareTo(Person o) {
      return (int) (getId() - o.getId());
   }
}

How to sort

Create a list of Persons and use Collections.sort method to sort the elements. 
package com.test.collection;

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

public class CustomSort {
    public static void main(String[] args) {
        List<Person> list = new ArrayList<Person>();
        list.add(new Person(10));
        list.add(new Person(2));
        list.add(new Person(15));
  
        System.out.println("Elements before sorting : ");
        for(Person i : list)
           System.out.print(" "+i.getId());
        Collections.sort(list); 
        System.out.println("\nElements after sorting : ");
        for(Person i : list)
           System.out.print(" "+i.getId());
    }
}

Output will be

Elements before sorting : 
 10 2 15
Elements after sorting : 
 2 10 15

Example Using Comparator interface

Student Object - Which is used in Collection 

package com.test.collection;

public class Student {
     private long id;
     public Student(long id) {
       this.id = id;
     }
     //Getters and setters
}

StundetComparator class - Implementing Comparator interface of type Student 

package com.test.collection;

import java.util.Comparator;

public class StudentComparator implements Comparator<Student> {
   public int compare(Student o1, Student o2) {
        return (int) (o1.getId() - o2.getId());
   }
}

How to sort

package com.test.collection;

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

public class CustomSort {
    public static void main(String[] args) {
      List<Student> list = new ArrayList<Student>();
      list.add(new Student(10));
      list.add(new Student(2));
      list.add(new Student(15));
  
      System.out.println("Elements before sorting : ");
      for(Student i : list)
         System.out.print(" "+i.getId());
      Collections.sort(list,new StudentComparator()); 
      System.out.println("\nElements after sorting : ");
      for(Student i : list)
         System.out.print(" "+i.getId());
   }
}

Output will be

Elements before sorting : 
 10 2 15
Elements after sorting : 
 2 10 15

Comparision

The implementation looks very similar, lets see the similarities and differences between them
Description Comparbale Comparator
Package java.lang.Comparable java.util.Comparator
Implementation
Need to implement in the same where which to be compared. 
Need to implement in separate Class
Arguments
Takes only one argument as the same type where it is implemented. Need to compare with itself and return an integer value
Takes two arguments of same type and should returns an integer value after comparing them.
Collection.sort
No extra arguments are required during sort. Collection.sort uses the compareTo method implemented to sort
Collection.sort requires this object as second argument to sort the Collection which is passed as first argument
Note: The Comparator should be of same type as the Collection.
Sorting
Always sort based on the compareTo method
Sorting will be done based on the comparator object passed in the second argument. So several Comparators can be created with each has it’s sorting logic. Based on the criteria, we can pass any comparator which is required.

Happy Learning!!!

No comments:

Post a Comment