Saturday, September 21, 2024
Google search engine
HomeLanguagesJavaComparator reversed() method in Java with examples

Comparator reversed() method in Java with examples

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

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments