Java Comparator reverseOrder() Method
Example
Sort a list in reverse alphabetical order:
import java.util.ArrayList;
import java.util.Comparator;
public class Main {
public static void main(String[] args) {
ArrayList<String> cars = new ArrayList<String>();
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
cars.add("Mazda");
cars.sort(Comparator.reverseOrder());
System.out.println(cars);
}
}
Definition and Usage
The reverseOrder() method returns a comparator that sorts objects in the reverse of their natural order: strings from Z to A, and numbers from large to small.
It works the same way as Collections.reverseOrder(), which is used in the List Sorting chapter.
Tip: To reverse any comparator, for example one that sorts cars by year, use reversed().
Syntax
public static <T extends Comparable<? super T>> Comparator<T> reverseOrder()
T refers to the data type of the objects to sort. It must be a type that implements Comparable, like String or Integer.
Parameter Values
None.
Technical Details
| Returns: | A Comparator that sorts objects in the reverse of their natural order. |
|---|
Related Pages
Java Advanced Sorting Tutorial
Java Lambda Expressions Tutorial
❮ Comparator Methods