Comparator in java

In this post, we will see  how you can use comparator to sort list of objects in java.

Comparator:

When you want to sort list of objects of a class.You can use 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.We will see more about it later. 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());
                }
            });

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

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());
      
   }
 }

}
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

Anonymous Comparator:

One of advantage of Comparator over comparable is you can create anonymous comparator i.e you don't need to implement Comparable interface to any class.You just need to pass objects to compare method. Lets understand more with help of example:

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.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 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());
  }

  //Sort by countryName
  // Anonymous Comparator
  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 name : 
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 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

So here we have created anonymous Comparator to sort country by name. We have not implemented Comparator to Country class , neither we have created any Comparator specific class.

Written by Arpit:

If you have read the post and liked it. Please connect with me on Facebook | Twitter | Google Plus

 

Java tutorial for beginners Copyright © 2012