Java Comparator reversed() Method
Example
Sort a list of cars by year, newest first:
import java.util.ArrayList;
import java.util.Comparator;
public class Main {
static class Car {
String brand;
int year;
Car(String brand, int year) {
this.brand = brand;
this.year = year;
}
public String toString() {
return brand + " " + year;
}
}
public static void main(String[] args) {
Comparator<Car> byYear = Comparator.comparingInt(c -> c.year);
ArrayList<Car> myCars = new ArrayList<Car>();
myCars.add(new Car("BMW", 1999));
myCars.add(new Car("Honda", 2006));
myCars.add(new Car("Ford", 1970));
myCars.sort(byYear.reversed());
System.out.println(myCars);
}
}
Definition and Usage
The reversed() method returns a new comparator that sorts in the opposite order of the comparator that you call it on. The first comparator does not change.
For example, if a comparator sorts cars by year from old to new, the reversed comparator sorts them from new to old.
Tip: Save the comparator in a variable first, like in the example. If you call reversed() directly on comparingInt(), Java does not know the type of c, so you must write it: Comparator.comparingInt((Car c) -> c.year).reversed().
Syntax
public Comparator<T> reversed()
T refers to the data type of the objects to compare, for example Car or String.
Parameter Values
None.
Technical Details
| Returns: | A Comparator that sorts in the opposite order. |
|---|
Related Pages
Java Advanced Sorting Tutorial
Java Lambda Expressions Tutorial
❮ Comparator Methods