Java 8 Comparator comparing() example

In Java 8, the Comparator interface introduced the static comparing() method which provides a way to create comparators for a specific key extraction function. This method is generally used with lambda expressions or method references to define custom sorting orders. Here’s an example of how to use comparing() method. In this Java 8 Comparator comparing() example

Suppose we have a list of Person objects, with two fields name and age. We want to sort them based on their names and ages. We can use the comparing() method to create a comparator that compares Person objects based on their name or age.

import java.util.*;

class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    @Override
    public String toString() {
        return name + " (" + age + ")";
    }
}

public class ComparatorExample {
    public static void main(String[] args) {
        List<Person> persons = new ArrayList<>();
        persons.add(new Person("Alice", 30));
        persons.add(new Person("Bob", 25));
        persons.add(new Person("Charlie", 40));

        // Using comparing() with a lambda expression
        Comparator<Person> ageComparator = Comparator.comparing(person -> person.getAge());
        persons.sort(ageComparator);
        System.out.println("Sorted by age: " + persons);

        // Using comparing() with a method reference
        Comparator<Person> nameComparator = Comparator.comparing(Person::getName);
        persons.sort(nameComparator);
        System.out.println("Sorted by name: " + persons);
    }
}

Output:-

Sorted by age: [Bob (25), Alice (30), Charlie (40)]
Sorted by name: [Alice (30), Bob (25), Charlie (40)]

In this example, the comparing() method is used twice. Once with a lambda expression to create a comparator that compares Person objects based on their ages, and once with a method reference to create a comparator that compares based on their names.

Note that in Java 8, the Comparator interface also introduced the reversed() method, which allows you to reverse the natural order of the comparator. You can chain it after the comparing() method to sort in descending order.

Comparator<Person> reversedAgeComparator = Comparator.comparing(Person::getAge).reversed();
persons.sort(reversedAgeComparator);
System.out.println("Sorted by age (descending): " + persons);

Note – We can also perform sorting using thenComaparing() method for multiple fields. The thenComparing() method allows us to chain comparators to create more complex sorting orders. For example, we can sort a list of persons by age and then by name.

Comparator<Person> ageThenNameComparator = Comparator
        .comparingInt(Person::getAge)
        .thenComparing(Person::getName);

persons.sort(ageThenNameComparator);
System.out.println("Sorted by age, then by name: " + persons);

See docs.

That’s all about Java 8 Comparator comparing() example.