Wednesday, July 3, 2024
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() 

Nokonwaba Nkukhwana
Experience as a skilled Java developer and proven expertise in using tools and technical developments to drive improvements throughout a entire software development life cycle. I have extensive industry and full life cycle experience in a java based environment, along with exceptional analytical, design and problem solving capabilities combined with excellent communication skills and ability to work alongside teams to define and refine new functionality. Currently working in springboot projects(microservices). Considering the fact that change is good, I am always keen to new challenges and growth to sharpen my skills.
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments