Java Comparator Methods Example

In this source code example, we will show you the usage of important Java Comparator interface methods with examples.

The Comparator interface in Java provides a mechanism to define custom orderings for collections of objects, beyond their natural ordering. This becomes essential when you want to sort or order a collection based on specific attributes or fields of objects.

Java Comparator Interface - Important Methods

import java.util.Arrays;
import java.util.Comparator;

class Student {
    String name;
    int age;

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

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

public class ComparatorMethodsDemo {
    public static void main(String[] args) {
        Student[] students = {
            new Student("Rohan", 20),
            new Student("Amit", 22),
            new Student("Pooja", 19)
        };

        // 1. Using comparing() method
        Arrays.sort(students, Comparator.comparing(Student::getAge));
        System.out.println("Students sorted by age: " + Arrays.toString(students));

        // 2. Using thenComparing() method
        Arrays.sort(students, Comparator.comparing(Student::getAge).thenComparing(Student::getName));
        System.out.println("Students sorted by age, then name: " + Arrays.toString(students));

        // 3. Using reversed() method
        Arrays.sort(students, Comparator.comparing(Student::getAge).reversed());
        System.out.println("Students sorted by age in reverse: " + Arrays.toString(students));

        // 4. Using naturalOrder() method
        String[] fruits = {"Apple", "Mango", "Banana"};
        Arrays.sort(fruits, Comparator.naturalOrder());
        System.out.println("Fruits in natural order: " + Arrays.toString(fruits));
    }
}

Output:

Students sorted by age: [Pooja (19), Rohan (20), Amit (22)]
Students sorted by age, then name: [Pooja (19), Rohan (20), Amit (22)]
Students sorted by age in reverse: [Amit (22), Rohan (20), Pooja (19)]
Fruits in natural order: [Apple, Banana, Mango]

Explanation:

1. comparing(): This method accepts a function that extracts a key to be compared. Here, we're extracting the age of students.

2. thenComparing(): After the primary comparison (in our case by age), this method performs a secondary comparison (by name here) if the primary comparison results in a tie.

3. reversed(): It reverses the order of the elements based on the previous comparison criteria.

4. naturalOrder(): This method returns a comparator that imposes the natural ordering of the elements. It's useful when the elements themselves implement Comparable, as String does.

Comparator provides a set of utility methods that allow us to create and combine comparators in a more readable and flexible way.


Comments