Click here to Skip to main content
15,879,019 members
Articles / Programming Languages / Java

Difference between Comparator and Comparable in Java

Rate me:
Please Sign up or sign in to vote.
4.57/5 (5 votes)
25 Mar 2013CPOL3 min read 100K   5   7
Difference between Comparator and Comparable in java

One of the common interview question is "What are differences between Comparator and Comparable". or "How will you sort collection of employee objects by its id or name". For that we can use two interfaces, i.e., Comparator and Comparable. Before we actually see differences,let me give you brief introduction of both.

Comparable interface

Class whose objects to be sorted must implement this interface. In this, we have to implement compareTo(Object) method. For example:

Java
public class Country implements Comparable<Country>{
       @Override
    public int compareTo(Country country) {
        return (this.countryId < country.countryId ) ? -1: (this.countryId > country.countryId ) ? 1:0 ;
}}

If any class implements comparable inteface then collection of that object can be sorted automatically using Collection.sort() or Arrays.sort().Object will be sort on the basis of compareTo method in that class. Objects which implement Comparable in Java can be used as keys in a SortedMap like TreeMap or SortedSet like TreeSet without implementing any other interface.

Comparator interface

The class whose objects to be sorted do not need to implement this interface. Some third class can implement this interface to sort. E.g., CountrySortByIdComparator class can implement Comparator interface to sort collection of country object by id. For example:

Java
public class CountrySortByIdComparator implements Comparator<Country>{

    @Override
    public int compare(Country country1, Country country2) {
        
        return (country1.getCountryId() < country2.getCountryId() ) ? -1: 
           (country1.getCountryId() > country2.getCountryId() ) ? 1:0 ;
    }
}

Using Comparator interface, we can write different sorting based on different attributes of objects to be sorted. You can use anonymous comparator to compare at particular line of code. For example:

Java
Country indiaCountry=new Country(1, "India");
Country chinaCountry=new Country(4, "China");
Country nepalCountry=new Country(3, "Nepal");
Country bhutanCountry=new Country(2, "Bhutan");

List<Country> listOfCountries = new ArrayList<Country>();
listOfCountries.add(indiaCountry);
listOfCountries.add(chinaCountry);
listOfCountries.add(nepalCountry);
listOfCountries.add(bhutanCountry); 

//Sort by countryName

Collections.sort(listOfCountries,new Comparator<Country>() {

    @Override
    public int compare(Country o1, Country o2) {

        return o1.getCountryName().compareTo(o2.getCountryName());
    }
});

Comparator vs Comparable

Package
ParameterComparableComparator
Sorting logicSorting logic must be in same class whose objects are being sorted. Hence this is called natural ordering of objectsSorting logic is in separate class. Hence we can write different sorting based on different attributes of objects to be sorted. E.g. Sorting using id,name etc.
ImplementationClass whose objects to be sorted must implement this interface. e.g Country class needs to implement comparable to collection of country object by idClass whose objects to be sorted do not need to implement this interface. Some other class can implement this interface. E.g.-CountrySortByIdComparator class can implement Comparator interface to sort collection of country object by id
Sorting methodint compareTo(Object o1)
This method compares this object with o1 object and returns a integer. Its value has following meaning
  1. positive – this object is greater than o1
  2. zero – this object equals to o1
  3. negative – this object is less than o1
int compare(Object o1,Object o2)

This method compares o1 and o2 objects. and returns a integer.Its value has following meaning.

  1. positive – o1 is greater than o2
  2. zero – o1 equals to o2
  3. negative – o1 is less than o1 
Calling methodCollections.sort(List)
Here objects will be sorted on the basis of CompareTo method
Collections.sort(List, Comparator)
Here objects will be sorted on the basis of Compare method in Comparator
Java.lang.ComparableJava.util.Comparator  

Java code

For Comparable

We will create class country having attribute id and name. This class will implement Comparable interface and implement CompareTo method to sort collection of country object by id.

1. Country.java

Java
package org.arpit.javapostsforlearning;
//If this.c***ryId < country.countryId:then compare method will return -1
//If this.countryId > country.countryId:then compare method will return 1
//If this.countryId==country.countryId:then compare method will return 0
public class Country implements Comparable<Country>{
    int countryId;
    String countryName;
   
   
    public Country(int countryId, String countryName) {
        super();
        this.countryId = countryId;
        this.countryName = countryName;
    }

    @Override
    public int compareTo(Country country) {
       return (this.countryId < country.countryId ) ? -1: (this.countryId > country.countryId ) ? 1:0 ;
    }


    public int getCountryId() {
        return countryId;
    }


    public void setCountryId(int countryId) {
        this.countryId = countryId;
    }


    public String getCountryName() {
        return countryName;
    }


    public void setCountryName(String countryName) {
        this.countryName = countryName;
    }
   
}

2.ComparatorMain.java

Java
package org.arpit.javapostsforlearning;

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

public class ComparableMain {

 /**
  * @author Arpit Mandliya
  */
 public static void main(String[] args) {
   Country indiaCountry=new Country(1, "India");
   Country chinaCountry=new Country(4, "China");
   Country nepalCountry=new Country(3, "Nepal");
   Country bhutanCountry=new Country(2, "Bhutan");
   
         List<Country> listOfCountries = new ArrayList<Country>();
         listOfCountries.add(indiaCountry);
         listOfCountries.add(chinaCountry);
         listOfCountries.add(nepalCountry);
         listOfCountries.add(bhutanCountry);
  
         System.out.println("Before Sort  : ");
         for (int i = 0; i < listOfCountries.size(); i++) {
    Country country=(Country) listOfCountries.get(i);
    System.out.println("Country Id: "+country.getCountryId()+"||"+"Country name: "+country.getCountryName());
   }
         Collections.sort(listOfCountries);
         
         System.out.println("After Sort  : ");
         for (int i = 0; i < listOfCountries.size(); i++) {
    Country country=(Country) listOfCountries.get(i);
    System.out.println("Country Id: "+country.getCountryId()+"|| "+"Country name: "+country.getCountryName());
   }
 }

}

Output

Java
Before Sort  : 
Country Id: 1||Country name: India
Country Id: 4||Country name: China
Country Id: 3||Country name: Nepal
Country Id: 2||Country name: Bhutan
After Sort  : 
Country Id: 1|| Country name: India
Country Id: 2|| Country name: Bhutan
Country Id: 3|| Country name: Nepal
Country Id: 4|| Country name: China

For Comparator

We will create class country having attribute id and name and will create another class CountrySortByIdComparator which will implement Comparator interface and implement a compare method to sort collection of country object by id and we will also see how to use anonymous comparator.

1.Country.java 

Java
package org.arpit.javapostsforlearning;

public class Country{
    int countryId;
    String countryName;
    
    public Country(int countryId, String countryName) {
        super();
        this.countryId = countryId;
        this.countryName = countryName;
    }

    public int getCountryId() {
        return countryId;
    }


    public void setCountryId(int countryId) {
        this.countryId = countryId;
    }


    public String getCountryName() {
        return countryName;
    }


    public void setCountryName(String countryName) {
        this.countryName = countryName;
    }
    
} 

2.CountrySortbyIdComparator.java

package org.arpit.javapostsforlearning;

import java.util.Comparator;
//If country1.getCountryId()<country2.getCountryId():then compare method will return -1
//If country1.getCountryId()>country2.getCountryId():then compare method will return 1
//If country1.getCountryId()==country2.getCountryId():then compare method will return 0
 public class CountrySortByIdComparator implements Comparator<Country>{

    @Override
    public int compare(Country country1, Country country2) {
        
        return (country1.getCountryId() < country2.getCountryId() ) ? -1: (country1.getCountryId() > country2.getCountryId() ) ? 1:0 ;
    }

}

3.ComparatorMain.java

package org.arpit.javapostsforlearning;

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

public class ComparatorMain {

 /**
  * @author Arpit Mandliya
  */
 public static void main(String[] args) {
   Country indiaCountry=new Country(1, "India");
   Country chinaCountry=new Country(4, "China");
   Country nepalCountry=new Country(3, "Nepal");
   Country bhutanCountry=new Country(2, "Bhutan");
   
         List<Country> listOfCountries = new ArrayList<Country>();
         listOfCountries.add(indiaCountry);
         listOfCountries.add(chinaCountry);
         listOfCountries.add(nepalCountry);
         listOfCountries.add(bhutanCountry);
  
         System.out.println("Before Sort by id : ");
         for (int i = 0; i < listOfCountries.size(); i++) {
    Country country=(Country) listOfCountries.get(i);
    System.out.println("Country Id: "+country.getCountryId()+"||"+"Country name: "+country.getCountryName());
   }
         Collections.sort(listOfCountries,new CountrySortByIdComparator());
         
         System.out.println("After Sort by id: ");
         for (int i = 0; i < listOfCountries.size(); i++) {
    Country country=(Country) listOfCountries.get(i);
    System.out.println("Country Id: "+country.getCountryId()+"|| "+"Country name: "+country.getCountryName());
   }
         
         //Sort by countryName
         Collections.sort(listOfCountries,new Comparator<Country>() {

    @Override
    public int compare(Country o1, Country o2) {
     return o1.getCountryName().compareTo(o2.getCountryName());
    }
   });
   
   System.out.println("After Sort by name: ");
         for (int i = 0; i < listOfCountries.size(); i++) {
    Country country=(Country) listOfCountries.get(i);
    System.out.println("Country Id: "+country.getCountryId()+"|| "+"Country name: "+country.getCountryName());
   }
 }

}

Output:

Before Sort by id : 
Country Id: 1||Country name: India
Country Id: 4||Country name: China
Country Id: 3||Country name: Nepal
Country Id: 2||Country name: Bhutan
After Sort by id: 
Country Id: 1|| Country name: India
Country Id: 2|| Country name: Bhutan
Country Id: 3|| Country name: Nepal
Country Id: 4|| Country name: China
After Sort by name: 
Country Id: 2|| Country name: Bhutan
Country Id: 4|| Country name: China
Country Id: 1|| Country name: India
Country Id: 3|| Country name: Nepal

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
India India
I am a java developer and blogger.Love to connect with people interested in java,programming or blogging.You can visit my blog at http://java2blog.com/

Comments and Discussions

 
QuestionGood Implementaion code Pin
Member 934102810-Apr-15 0:02
Member 934102810-Apr-15 0:02 
GeneralComment on Comparator and comparator difference article Pin
Anil Nivargi1-Jul-14 8:39
Anil Nivargi1-Jul-14 8:39 
Suggestionnice article Pin
mobings15-Jan-14 8:26
mobings15-Jan-14 8:26 
GeneralNice article.... Pin
The Java Guru24-Sep-13 18:31
professionalThe Java Guru24-Sep-13 18:31 
GeneralRe: Nice article.... Pin
Arpit Mandliya24-Sep-13 19:35
Arpit Mandliya24-Sep-13 19:35 
GeneralMy Vote Pin
Java Experience28-Jul-13 23:08
Java Experience28-Jul-13 23:08 
GeneralMy vote of 4 Pin
Sudhakar Shinde22-Apr-13 20:48
Sudhakar Shinde22-Apr-13 20:48 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.