Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
communitycreator

What is the Comparator.reverseOrder method in Java?

abhilash

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Overview

reverseOrder is a static method of the Comparator class. It is used to return a Comparator that sorts the elements in the opposite of the natural order which is the reverse order.

The Comparator interface is defined in the java.util package. To import the Comparator interface check the following import statement.

import java.util.Comparator;

Syntax

public static <T extends Comparable<? super T>> Comparator<T> reverseOrder()

Parameters

This method has no parameters.

Returns

The method returns a Comparator.

Code

import java.util.Arrays;
import java.util.Comparator;
public class Main{
public static void main(String[] args) {
// Collection of strings
String[] strings = {"hello", "educative", "edpresso"};
// print the string collection
System.out.println("Before sorting: " + Arrays.toString(strings));
// Using the naturalOrder method to sort the array
Arrays.sort(strings, Comparator.naturalOrder());
// print the sorted array in natural order
System.out.println("After sorting in natural order: " + Arrays.toString(strings));
strings = new String[]{"hello", "educative", "edpresso"};
// Using the reverseOrder method to sort the array in reverse
Arrays.sort(strings, Comparator.reverseOrder());
// print the sorted array in reverse order
System.out.println("After sorting in reverse order: " + Arrays.toString(strings));
}
}
Implementation of the reverseOrder method

Explanation

  • Lines 1–2: We import the relevant classes and packages.
  • Line 8: We define an array of strings called strings.
  • Line 11: We print the strings array.
  • Line 14: We sort the strings array in the natural order.
  • Line 17: We print the sorted strings array.
  • Line 19: We redefine the strings array.
  • Line 22: We sort the strings array in the reverse order.
  • Line 25: We print the reverse sorted strings array.

RELATED TAGS

java
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring