What is the Comparator.reverseOrder method in Java?
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 stringsString[] strings = {"hello", "educative", "edpresso"};// print the string collectionSystem.out.println("Before sorting: " + Arrays.toString(strings));// Using the naturalOrder method to sort the arrayArrays.sort(strings, Comparator.naturalOrder());// print the sorted array in natural orderSystem.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 reverseArrays.sort(strings, Comparator.reverseOrder());// print the sorted array in reverse orderSystem.out.println("After sorting in reverse order: " + Arrays.toString(strings));}}
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
stringsarray. - Line 14: We sort the
stringsarray in the natural order. - Line 17: We print the sorted
stringsarray. - Line 19: We redefine the
stringsarray. - Line 22: We sort the
stringsarray in the reverse order. - Line 25: We print the reverse sorted
stringsarray.