Java Collections - reverseOrder() Method
The java.util.Collections.reverseOrder() method returns a comparator that imposes the reverse ordering of the specified comparator. If the specified comparator is null, this method is equivalent to reverseOrder() (in other words, it 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(Comparator<T> cmp)
Here, T is the type of element in the collection.
Parameters
cmp |
Specify a comparator who's ordering is to be reversed by the returned comparator or null. |
Return Value
Returns a comparator that imposes the reverse ordering of the specified comparator.
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(null); //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