The reversed() method of Comparator Interface in Java returns a comparator that imposes the reverse ordering of this comparator. If you use sort method of the array and passes this comparator after applying the reversed method then it will sort the array in reverse order.
Syntax:
default Comparator<T> reversed()
Parameters: This method accepts nothing.
Return value: This method returns a comparator that imposes the reverse ordering of this comparator.
Below programs illustrate reversed() method:
Program 1:
Java
// Java program to demonstrate// Comparator.reversed() methodimport java.util.*;public class GFG { public static void main(String[] args) { String[] Arraystrings = { "aman", "amar", "avik" }; System.out.println("before sort : " + Arrays.toString(Arraystrings)); Comparator<String> comp = (String::compareTo); Arrays.sort(Arraystrings, comp.reversed()); System.out.println("after sort : " + Arrays.toString(Arraystrings)); }} |
before sort : [aman, amar, avik] after sort : [avik, amar, aman]
Program 2:
Java
// Java program to demonstrate// Comparator.reversed() methodimport java.util.*;public class GFG { public static void main(String[] args) { String[] list = { "KKR", "CSK", "MI", "KXIP", "RCB", "SRH", "DC", "RR" }; System.out.println("Before sorting:"); System.out.println(Arrays.toString(list)); Comparator<String> comp = (String::compareTo); Arrays.sort(list, comp.reversed()); System.out.println("After sorting:"); System.out.println(Arrays.toString(list)); }} |
Before sorting: [KKR, CSK, MI, KXIP, RCB, SRH, DC, RR] After sorting: [SRH, RR, RCB, MI, KXIP, KKR, DC, CSK]
References: https://docs.oracle.com/javase/10/docs/api/java/util/Comparator.html#reversed()

… [Trackback]
[…] Find More to that Topic: geeksforgeeks.org/comparator-reversed-method-in-java-with-examples-2/ […]
… [Trackback]
[…] Info on that Topic: geeksforgeeks.org/comparator-reversed-method-in-java-with-examples-2/ […]
… [Trackback]
[…] Here you can find 60335 additional Info on that Topic: geeksforgeeks.org/comparator-reversed-method-in-java-with-examples-2/ […]
… [Trackback]
[…] Find More Info here on that Topic: geeksforgeeks.org/comparator-reversed-method-in-java-with-examples-2/ […]
… [Trackback]
[…] Information to that Topic: geeksforgeeks.org/comparator-reversed-method-in-java-with-examples-2/ […]
… [Trackback]
[…] There you will find 7413 additional Information to that Topic: geeksforgeeks.org/comparator-reversed-method-in-java-with-examples-2/ […]