Collections.reverseOrder() in Java with Examples

// Returns a comparator that imposes the reverse of
// the natural ordering on a collection of objects
// that implement the Comparable interface.
// The natural ordering is the ordering imposed by
// the objects' own compareTo method
public static Comparator reverseOrder()

We can the comparator returned by Collections.reverseOrder() to sort a list in descending order.

// Java program to demonstrate working of Collections.reveseOrder()

// to sort a list in descending order

importjava.util.*;

publicclassCollectionsorting

{

publicstaticvoidmain(String[] args)

{

// Create a list of Integers

ArrayList<Integer> al = newArrayList<Integer>();

al.add(30);

al.add(20);

al.add(10);

al.add(40);

al.add(50);

/* Collections.sort method is sorting the

elements of ArrayList in descending order. */

Collections.sort(al, Collections.reverseOrder());

// Let us print the sorted list

System.out.println("List after the use of Collection.reverseOrder()"+

" and Collections.sort() :\n"+ al);

}

}

Output:

List after the use of Collection.reverseOrder() and Collections.sort():
[50, 40, 30, 20, 10]

System.out.println("Array after the use of Collection.reverseOrder()"+

" and Arrays.sort() :\n"+ Arrays.toString(arr));

}

}

Output:

Array after the use of Collection.reverseOrder() and Arrays.sort() :
[40, 30, 20, 10]

public static Comparator reverseOrder(Comparator c)

It returns a Comparator that imposes reverse order of a passed Comparator object. We can use this method to sort a list in reverse order of user defined Comparator. For example, in the below program, we have created a reverse of user defined comparator to sort students in descending order of roll numbers.

This article is contributed by Mohit Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
.