Package relations: + java.util + - java.lang.Comparator<T>

Parameter type: T - the type of objects that may be compared by this comparator

This is a functional interface.


The Comparator is a functional interface that used to define a custom ordering for objects. This interface is useful for sorting a collection of objects that is different from their natural ordering, or when objects do not have a natural ordering using collections sort. The Comparator interface has a single abstract method compare() and several default methods.

Difference between Comparable and Comparator

compare()

The compare() is an abstract method that compares two arguments for order.

int compare(T o1, T o2)

This method returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.

Implement with anonymous nested class

You can implement the Comparator interface and override the compare() method using anonymous nested class.

public class Person {  
    int age;  
    String name;  
    
    public Person(int age, String name) {  
        this.age = age;  
        this.name = name;  
    }  
    
    @Override  
    public String toString() {  
        return "[" + "Name: " + name + ", Age: " + age + "]";  
    }  
}
public static void main(String[] args) {  
    List<Person> people = new ArrayList<>();  
    people.add(new Person(12, "Tim"));  
    people.add(new Person(31, "John"));  
    people.add(new Person(23, "Jason"));  
	
	// implement using anonymous nested class
    Comparator<Person> ageComparator = new Comparator<Person>() {  
        @Override  
        public int compare(Person o1, Person o2) {  
            return Integer.compare(o1.age, o2.age);  
        }  
    };
    // sort with collections
    Collections.sort(people, ageComparator);  
	System.out.println(people);
}
[[Name: Tim, Age: 12], [Name: Jason, Age: 23], [Name: John, Age: 31]]

Implement with lambda expression

The below is the implementation of the Comparator interface using lambda expression.

public static void main(String[] args) {  
    List<Person> people = new ArrayList<>();  
    people.add(new Person(12, "Tim"));  
    people.add(new Person(31, "John"));  
    people.add(new Person(23, "Jason"));  
	
	// implement using lambda expression
	Comparator<Person> ageComparator = (Person o1, Person o2) -> Integer.compare(o1.age, o2.age); 
    Collections.sort(people, ageComparator);  
	System.out.println(people);
}
[[Name: Tim, Age: 12], [Name: Jason, Age: 23], [Name: John, Age: 31]]

We can also use the static method comparingInt() that comes with the Comparator interface to replace the compare() method from Integer class.

Comparator<Person> ageComparator = Comparator.comparingInt((Person o) -> o.age);

The comparingInt() takes a function (or lambda expression) that extracts an int from a Person object. In this case, the lambda (Person o) -> o.age extracts the age, and it returns a Comparator that compares by the age value.

Comparator default methods

MethodDescription
static <T> Comparator<T> comparingInt(ToIntFunction<? super T> keyExtractor)It accepts a function that extracts an int sort key from a type T, and returns a Comparator that compares by that sort key
static <T> Comparator<T> comparingDouble(ToDoubleFunction<? super T> keyExtractor)It accepts a function that extracts a double sort key from a type T, and returns a Comparator that compares by that sort key

Back to parent page: Java Standard Edition (Java SE) and Java Programming

Web_and_App_DevelopmentProgramming_LanguagesJavaComparatorLambda_ExpressionAnonymous_Nested_Class