Java Utility Library

Java Collections - reverseOrder() Method



The java.util.Collections.reverseOrder() method returns a comparator that imposes the reverse of the natural ordering on a collection of objects that implement the Comparable interface.

Syntax

public static <T> Comparator<T> reverseOrder()

Here, T is the type of element in the collection.


Parameters

No parameter is required.

Return Value

Returns a comparator that imposes the reverse of the natural ordering on a collection of objects that implement the Comparable interface.

Exception

NA.

Example:

In the example below, the java.util.Collections.reverseOrder() method is used to perform reverse order sorting of elements of the given list.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating a list object
    List<Integer> MyList = new ArrayList<Integer>();

    //populating MyList
    MyList.add(10);
    MyList.add(20);
    MyList.add(40);
    MyList.add(30);
    MyList.add(50);

    //printing the MyList
    System.out.println("MyList contains: " + MyList); 

    //creating a comparator for reverse of 
    //the natural ordering sorting
    Comparator<Integer> comp = Collections.reverseOrder();

    //reverse sort MyList
    Collections.sort(MyList, comp);

    //printing the MyList
    System.out.println("MyList contains: " + MyList); 
  }
}

The output of the above code will be:

MyList contains: [10, 20, 40, 30, 50]
MyList contains: [50, 40, 30, 20, 10]

❮ Java.util - Collections