Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Comparator reversed() method in Java with examples

  • Last Updated : 05 Feb, 2021

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:  

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.

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()  method
 
import 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));
    }
}
Output
before sort : [aman, amar, avik]
after sort : [avik, amar, aman]

Program 2: 

Java




// Java program to demonstrate
// Comparator.reversed()  method
 
import 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));
    }
}
Output
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() 




My Personal Notes arrow_drop_up
Recommended Articles
Page :