Java Comparator Reverse Order Example

In this source code example, you will learn how to reverse the order with the Java Comparator interface.

Using Comparator, we can easily reverse the sorting order, either by leveraging the natural ordering of elements or by applying custom sorting logic.

Reversing Order using Java's Comparator Interface

Here's a demonstration showcasing how to reverse the order with the Comparator interface:

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 ReverseOrderComparatorDemo {
    public static void main(String[] args) {
        Student[] students = {
            new Student("Rohan", 20),
            new Student("Amit", 22),
            new Student("Pooja", 19)
        };

        // 1. Reversing natural order using Comparator
        Arrays.sort(students, Comparator.reverseOrder());
        System.out.println("Students in reverse natural order: " + Arrays.toString(students));

        // 2. Reversing custom order (by age) using Comparator
        Comparator<Student> ageComparator = Comparator.comparingInt(Student::getAge);
        Arrays.sort(students, ageComparator.reversed());
        System.out.println("Students sorted by age in reverse: " + Arrays.toString(students));
    }
}

Output:

Students in reverse natural order: [Rohan (20), Pooja (19), Amit (22)]
Students sorted by age in reverse: [Amit (22), Rohan (20), Pooja (19)]

Explanation:

1. Reversing natural order: The method Comparator.reverseOrder() returns a comparator that imposes the reverse of the natural ordering on a collection of objects that implement the Comparable interface. Here, since the Student doesn't implement Comparable, the output is unpredictable.

2. Reversing custom order: First, we create a custom comparator ageComparator to sort students by their age. We then use the reversed() method on this comparator to get a new comparator that sorts students in descending order of age.


Comments