Tuesday 22 July 2014

Comparable Vs Comparator in Java

Before discussing about the differences will see example of each.

Comparable interface
Comparable interface is implemented by a class used to compare objects of this class. If any class implements comparable interface then collection of that object can be sorted automatically using Collection.sort() or Arrays.sort() using the implemented compareTo logic.

import java.util.*;

public class Employee implements Comparable<Employee>{

    String firstName, lastName;
    Integer id;
    
    Employee(String firstName, String lastName, int id){
        this.firstName = firstName;
        this.lastName = lastName;
        this.id = id;
    }
    
    @Override
    public int compareTo(Employee o) {
        if(o == null)
            throw new NullPointerException();
       return this.id.compareTo(o.id);
    }
    
    @Override
    public String toString(){
      return id +". " + firstName +" " + lastName;  
    }
    
    public static void main(String args[]){
        List<Employee> myList = new ArrayList<> ();
        
        myList.add(new Employee("Joel","Abc", 5));
        myList.add(new Employee("Murali","Krishna", 3));
        myList.add(new Employee("Gopi","battu", 4));
        myList.add(new Employee("Rama","Krishna", 2));
        
        System.out.println("Before Sorting");
        Iterator<Employee> iter1 = myList.iterator();
        while(iter1.hasNext()){
            System.out.println(iter1.next());
        }
        
        Collections.sort(myList);
        
        System.out.println("\nAfter Sorting");
        Iterator<Employee> iter2 = myList.iterator();
        while(iter2.hasNext()){
            System.out.println(iter2.next());
        }
        
    }
}

Output
Before Sorting
5. Joel Abc
3. Murali Krishna
4. Gopi battu
2. Rama Krishna

After Sorting
2. Rama Krishna
3. Murali Krishna
4. Gopi battu
5. Joel Abc

Comparator interface
Comparator interface provides facility to compare objects based on different attributes. Classes implements this interface must provide implementation for compare(T o1, T o2).

import java.util.*;

public class FirstNameComparator implements Comparator<Employee>{
    @Override
    public int compare(Employee e1, Employee e2){
        return e1.firstName.compareTo(e2.firstName);
    }
}

import java.util.Comparator;

public class LastNameComparator implements Comparator<Employee>{
    @Override
    public int compare(Employee e1, Employee e2){
        return e1.lastName.compareTo(e2.lastName);
    }
}

import java.util.*;

public class Employee implements Comparable<Employee>{

    String firstName, lastName;
    Integer id;
    
    Employee(String firstName, String lastName, int id){
        this.firstName = firstName;
        this.lastName = lastName;
        this.id = id;
    }
    
    @Override
    public int compareTo(Employee o) {
        if(o == null)
            throw new NullPointerException();
       return this.id.compareTo(o.id);
    }
    
    @Override
    public String toString(){
      return id +". " + firstName +" " + lastName;  
    }
    
    public static void main(String args[]){
        List<Employee> myList = new ArrayList<> ();
        FirstNameComparator cmp1 = new FirstNameComparator();
        LastNameComparator cmp2 = new LastNameComparator();
        
        myList.add(new Employee("Joel","Abc", 5));
        myList.add(new Employee("Murali","Krishna", 3));
        myList.add(new Employee("Gopi","Battu", 4));
        myList.add(new Employee("Rama","Krishna", 2));
        
        System.out.println("Before Sorting");
        Iterator<Employee> iter1 = myList.iterator();
        while(iter1.hasNext()){
            System.out.println(iter1.next());
        }
        
        myList.sort(cmp1);
        System.out.println("Sorting by using first name comparator");
        Iterator<Employee> iter2 = myList.iterator();
        while(iter2.hasNext()){
            System.out.println(iter2.next());
        }
        
        myList.sort(cmp2);
        System.out.println("Sorting by using last name comparator");
        Iterator<Employee> iter3 = myList.iterator();
        while(iter3.hasNext()){
            System.out.println(iter3.next());
        }
        
        Collections.sort(myList);
        System.out.println("Sorting by using id comparator");
        Iterator<Employee> iter4 = myList.iterator();
        while(iter4.hasNext()){
            System.out.println(iter4.next());
        }
    }
}

Output
Before Sorting
5. Joel Abc
3. Murali Krishna
4. Gopi Battu
2. Rama Krishna
Sorting by using first name comparator
4. Gopi Battu
5. Joel Abc
3. Murali Krishna
2. Rama Krishna
Sorting by using last name comparator
5. Joel Abc
4. Gopi Battu
3. Murali Krishna
2. Rama Krishna
Sorting by using id comparator
2. Rama Krishna
3. Murali Krishna
4. Gopi Battu
5. Joel Abc

Differences
  1. Comparable interface is in java.lang package, Comparator interface is in java.util package.
  2. Sorting logic must be in same class to implement Comparable. Sorting logic do not need to be in same class to implement Comparator interface.
  3. Comparable interface has 'compareTo(T o)' method. Comparator interface has ' compare(T o1, T o2) '
  1. Use Comparable if you want to define a default (natural) ordering behaviour of the object. Use Comparator if you want to define an external controllable ordering behaviour.
  2. Use Comparator when you want comparing behaviour different from the default.
Related Articles
Sort HashMap by Key and value 
Sort list of objects with multiple fields 
Sort list in java 
Convert list to set 
Convert list to Integer Array



                                                 Home

No comments:

Post a Comment