Java Collections reverseOrder() Method

The reverseOrder() method in Java is a utility method provided by the java.util.Collections class. It returns a Comparator that imposes the reverse order of a collection of objects. There are two variants of this method: one that reverses the natural ordering of the elements and another that reverses the order imposed by a specified comparator.

Table of Contents

  1. Introduction
  2. reverseOrder() Method Syntax
  3. Examples
    • Basic Usage of reverseOrder() with Natural Ordering
    • Using reverseOrder() with Custom Comparator
  4. Real-World Use Case
  5. Conclusion

Introduction

The Collections.reverseOrder() method provides an easy way to obtain a comparator that can sort a collection in descending order. It is useful when you need to sort a collection in reverse order, either by reversing the natural order or by reversing a custom-defined order using a comparator.

The reverse order comparator changes the order of sorting for collections that implement the Comparable interface or that can be sorted using a Comparator.

reverseOrder() Method Syntax

Variant 1: Reverse Natural Ordering

public static <T> Comparator<T> reverseOrder()
  • Returns:
    • A comparator that imposes the reverse of the natural ordering on a collection of objects that implement the Comparable interface.

Variant 2: Reverse Custom Comparator

public static <T> Comparator<T> reverseOrder(Comparator<T> cmp)
  • Parameters:

    • cmp: The comparator whose ordering is to be reversed.
  • Returns:

    • A comparator that imposes the reverse ordering of the specified comparator.

Examples

Basic Usage of reverseOrder() with Natural Ordering

The following example demonstrates how to use the reverseOrder() method to sort a list of integers in descending order using natural ordering.

Example

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class ReverseOrderExample {
    public static void main(String[] args) {
        // Create a list of integers
        List<Integer> numbers = new ArrayList<>();
        Collections.addAll(numbers, 5, 2, 8, 1, 9);

        // Display the original list
        System.out.println("Original List: " + numbers);

        // Sort the list in descending order using reverseOrder()
        Collections.sort(numbers, Collections.reverseOrder());

        // Display the sorted list
        System.out.println("Sorted List (Descending): " + numbers);
    }
}

Output:

Original List: [5, 2, 8, 1, 9]
Sorted List (Descending): [9, 8, 5, 2, 1]

Using reverseOrder() with Custom Comparator

You can also use the reverseOrder(Comparator<T> cmp) method to reverse the ordering imposed by a custom comparator.

Example

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

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 CustomReverseOrderExample {
    public static void main(String[] args) {
        // Create a list of students
        List<Student> students = new ArrayList<>();
        students.add(new Student("Amit", 20));
        students.add(new Student("Neha", 22));
        students.add(new Student("Raj", 19));

        // Define a comparator to compare students by age
        Comparator<Student> ageComparator = Comparator.comparingInt(student -> student.age);

        // Display the original student list
        System.out.println("Original Student List: " + students);

        // Sort the list in ascending order of age using the custom comparator
        Collections.sort(students, ageComparator);
        System.out.println("Sorted by Age (Ascending): " + students);

        // Sort the list in descending order of age using reverseOrder() with a custom comparator
        Collections.sort(students, Collections.reverseOrder(ageComparator));
        System.out.println("Sorted by Age (Descending): " + students);
    }
}

Output:

Original Student List: [Amit (20), Neha (22), Raj (19)]
Sorted by Age (Ascending): [Raj (19), Amit (20), Neha (22)]
Sorted by Age (Descending): [Neha (22), Amit (20), Raj (19)]

Explanation:

  1. Natural Ordering: In the first example, the reverseOrder() method is used to sort a list of integers in descending order using their natural ordering.

  2. Custom Comparator: In the second example, a custom comparator is defined to sort students by age. The reverseOrder(Comparator<T> cmp) method is used to sort the students in descending order of age by reversing the custom comparator’s ordering.

Real-World Use Case

Sorting Products by Price in Descending Order

In real-world applications, the reverseOrder() method can be used to sort a collection of objects, such as products, by a specific attribute, such as price, in descending order.

Example

Imagine a scenario where you need to sort a list of products by price from highest to lowest.

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

class Product {
    String name;
    double price;

    Product(String name, double price) {
        this.name = name;
        this.price = price;
    }

    @Override
    public String toString() {
        return name + " (Price: $" + price + ")";
    }
}

public class ProductExample {
    public static void main(String[] args) {
        // Create a list of products
        List<Product> products = new ArrayList<>();
        products.add(new Product("Laptop", 1500.00));
        products.add(new Product("Smartphone", 800.00));
        products.add(new Product("Tablet", 600.00));

        // Define a comparator to compare products by price
        Comparator<Product> priceComparator = Comparator.comparingDouble(product -> product.price);

        // Sort the list in descending order of price using reverseOrder() with a custom comparator
        Collections.sort(products, Collections.reverseOrder(priceComparator));

        // Display the sorted list of products
        System.out.println("Products Sorted by Price (Descending): " + products);
    }
}

Output:

Products Sorted by Price (Descending): [Laptop (Price: $1500.0), Smartphone (Price: $800.0), Tablet (Price: $600.0)]

Explanation:

  1. Product List: The list contains products with their respective prices.

  2. Custom Comparator: The comparator compares products by their price.

  3. Descending Order: The reverseOrder(Comparator<T> cmp) method is used to sort the products in descending order of price.

Conclusion

The Collections.reverseOrder() method is a powerful utility for sorting collections in reverse order in Java. By providing a simple way to obtain a reverse order comparator, it enhances the flexibility and readability of your code. This method is particularly valuable in scenarios where you need to sort collections in descending order, whether by natural ordering or custom-defined ordering, improving the robustness and maintainability of your Java applications.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top