Get reverse order using Comparator in Java


The objects of a user defined class can be ordered using the Comparator interface in Java. The java.util.Collections.reverseOrder() method reverses the order of an element collection using a Comparator.

A program that demonstrates this is given as follows −

Example

import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
public class Demo {
   public static void main(String args[]) throws Exception {
      Comparator comparator = Collections.reverseOrder(); { "John", "Amy", "Susan", "Peter" };
      int n = str.length;
      System.out.println("The array elements are: ");
      for (int i = 0; i < n; i++) {
         System.out.println(str[i]);
      }
      Arrays.sort(str, comparator);
      System.out.println("
The array elements sorted in reverse order are: ");       for (int i = 0; i < n; i++) {          System.out.println(str[i]);       }    } }

The output of the above program is as follows −

The array elements are:
John
Amy
Susan
Peter
The array elements sorted in reverse order are:
Susan
Peter
John
Amy

Now let us understand the above program.

The Comparator is created along with reverseOrder() method. Then the string array str[] is defined and then the elements are displayed using a for loop. A code snippet which demonstrates this is as follows −

Comparator comparator = Collections.reverseOrder(); { "John", "Amy", "Susan", "Peter" };
int n = str.length;
System.out.println("The array elements are: ");
for (int i = 0; i < n; i++) {
System.out.println(str[i]);
}

The string array is sorted in reverse order using the java.util.Arrays.sort() method. Then the array elements are displayed using a for loop. A code snippet which demonstrates this is as follows −

Arrays.sort(str, comparator);
System.out.println("
The array elements sorted in reverse order are: "); for (int i = 0; i < n; i++) {    System.out.println(str[i]); }

Vikyath Ram
Vikyath Ram

A born rival

Updated on: 30-Jun-2020

484 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements