Collections.reverseOrder() in Java with Examples
The reverseOrder() method of Collections class that in itself is present inside java.util package returns a comparator and using this comparator we can order the Collection in reverse order. Natural ordering is the ordering imposed by the objects’ own compareTo method.
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
public static Comparator reverseOrder()
Parameter: A comparator whose ordering is to be reversed by the returned comparator(it can also be null)
Return Type: A comparator that imposes the reverse of the natural ordering on a collection of objects that implement the Comparable interface.
Now in order to dig deeper to understand to grassroots, we will be covering different use-cases s listed below as follows:
- To sort a list in descending order
- To Sort an Array in Descending Order
- To sort students in descending order of roll numbers when there is a user-defined comparator to do reverse.
Case 1: To sort a list in descending order
List after the use of Collection.reverseOrder() and Collections.sort() : [50, 40, 30, 20, 10]
Note: Geeks now you must be thinking that can we use Arrays.sort()?
Arrays.sort() cannot be used directly to sort primitive arrays in descending order. If we try to call the Arrays.sort() method by passing reverse Comparator defined by Collections.reverseOrder(), it will throw the error as shown below as follws:
Tip: But this will work fine with ‘Array of Objects’ such as the Integer array but will not work with a primitive array such as the int array.
Case 2: To Sort an Array in Descending Order
Array after the use of Collection.reverseOrder() and Arrays.sort() : [40, 30, 20, 10]
Case 3: To sort students in descending order of roll numbers when there is a user-defined comparator to do reverse.
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 the user-defined comparator to sort students in descending order of roll numbers.
Unsorted 111 bbbb london 131 aaaa nyc 121 cccc jaipur Sorted by rollno 131 aaaa nyc 121 cccc jaipur 111 bbbb london
The key thing here to remember is above program uses unchecked and unsafe operations.
This article is contributed by Mohit Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.