Arpit Mandliya

About Arpit Mandliya

I am java developer at Tata Consultancy Services Ltd. My current area of interest are J2EE,web development and java design patterns. I am technology enthusiast trying to explore new technologies. In spare time,I love blogging.

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:
 
 
 

public class Country implements Comparable{
       @Override
    public int compareTo(Object arg0) {
        Country country=(Country) arg0;
        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: 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:

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:

         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

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 method
int 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
PackageJava.lang.Comparable

 

Java.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

package org.arpit.javapostsforlearning;
//If this.cuntryId < 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{
    int countryId;
    String countryName;

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

    @Override
    public int compareTo(Object arg0) {
        Country country=(Country) arg0;
        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

package org.arpit.javapostsforlearning;

import java.util.ArrayList;
import java.util.Collections;
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  : ');
	        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:

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 compare method to sort collection of country object by id and we will also see how to use anonymous comparator.

1.Country.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

 

Reference: Difference between Comparator and Comparable in Java from our JCG partner Arpit Mandliya at the Java frameworks and design patterns for beginners blog.

Related Whitepaper:

Bulletproof Java Code: A Practical Strategy for Developing Functional, Reliable, and Secure Java Code

Use Java? If you do, you know that Java software can be used to drive application logic of Web services or Web applications. Perhaps you use it for desktop applications? Or, embedded devices? Whatever your use of Java code, functional errors are the enemy!

To combat this enemy, your team might already perform functional testing. Even so, you're taking significant risks if you have not yet implemented a comprehensive team-wide quality management strategy. Such a strategy alleviates reliability, security, and performance problems to ensure that your code is free of functionality errors.Read this article to learn about this simple four-step strategy that is proven to make Java code more reliable, more secure, and easier to maintain.

Get it Now!  

12 Responses to "Difference between Comparator and Comparable in Java"

  1. Vipul Shukla says:

    Hi Arpit,

    I have a doubt here. even in case of comparable, we can sort the object based on its attributes…like countryId in this case. Does this mean that the main difference is that we can only choose to sort using one attribute in case of comparable, however in case of comparator we can provide various implementations of compare method??

    • Jai says:

      Yes, but in different classes. like below.

      ///Sort by ID
      public class CountrySortByIdComparator implements Comparator{

      public int compare(Country country1, Country country2) {
      // your logic
      }

      //Sort By Name
      public class CountrySortByNameComparator implements Comparator{

      public int compare(Country country1, Country country2) {
      // your logic
      }

      //Sort By Designation
      public class CountrySortByDesignationComparator implements Comparator{

      public int compare(Country country1, Country country2) {
      // your logic
      }

      ///// Some where in other class’s Main

      Collections.sort(listOfCountries,new CountrySortByIdComparator());

      Collections.sort(listOfCountries,new CountrySortByNameComparator());

      Collections.sort(listOfCountries,new CountrySortByDesignationComparator());

  2. Prem Kumar says:

    Comparator is easy to understand but sometimes a bit confusing because of the difficult to grab documentation from oracle or earlier Sun. It is one of the most important things you need to know while working with java.

    Try reading it here http://javahash.com/java-comparator-and-comparable-demystified/

  3. pops says:

    very good explaination

  4. Yogesh says:

    Excellent!!!

  5. ashish says:

    hey dude ,
    Please remove the line numbers from the above code as those line no are also getting copied while copying the code

  6. Dilip Senapati says:

    Very good explanation, will be very beneficial for java learners.

  7. Girish says:

    Very good explanation …..Thanks to all……

  8. nani says:

    please change the name of the class to ComparableMain instead of comparatorMain in the first sort program. That created a lot of disturbance for me to understand

  9. vysh says:

    very good and detailed article

  10. Aamir says:

    Very good explanation, but I have a question. As everyone keep saying that compareTo method returns positive, negative etc values. I am just curious about who needs those values , I mean we simply call a sort method and the class whose objects we wanna sort implements comparable interface and we simply say in compareTo() method if one objects attrib is less or whatever than other then return something, ok if i have 10 objects in my list and in compareTo() we are saying the same thing as said above, then are first two objects in list first compared or something else happens .

Leave a Reply


9 − = two



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.

Sign up for our Newsletter

15,153 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books