Java Comparator Interface
Java comparator interface is used in a situation when we have to sort an object which does not implement Comparable or do sorting in a different way than the Comparable.
Comparator is a functional interface since it has only one abstract method compare(). It takes two augments and resides in java.util package.
Example of comparator:
import java.util.*; public class Country implements Comparable<Country> { private String name; private int polulation; public Country(String name, int pop) { this.name = name; this.polulation = pop; } public int getPopulation() { return polulation; } public String toString() { return name; } public int compareTo(Country d) { return name.compareTo(d.name); } static Comparator<Country> byPopulation = new Comparator<Country>() { public int compare(Country c1, Country c2) { return c1.getPopulation()- c2.getPopulation(); }}; public static void main(String[] args) { List<Country> c = new ArrayList<>(); c.add(new Country("INDIA",1000)); c.add(new Country("CHINA",20000)); Collections.sort(c);// sort by name System.out.println(c);// [CHINA, INDIA] Collections.sort(c,byPopulation); System.out.println(c); } }
Output:
[CHINA, INDIA] // Comparable interface [INDIA, CHINA] // Comparator interface