Skip to content
Related Articles

Related Articles

Comparator reversed() method in Java with examples

View Discussion
Improve Article
Save Article
  • Last Updated : 05 Feb, 2021
View Discussion
Improve Article
Save Article

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()  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 :

Start Your Coding Journey Now!