Java Comparator thenComparing() Method
Example
Sort cars by brand, and cars with the same brand by year:
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> byBrand = Comparator.comparing(c -> c.brand);
ArrayList<Car> myCars = new ArrayList<Car>();
myCars.add(new Car("Ford", 2006));
myCars.add(new Car("BMW", 1999));
myCars.add(new Car("Ford", 1970));
myCars.sort(byBrand.thenComparing(c -> c.year));
System.out.println(myCars);
}
}
Definition and Usage
The thenComparing() method returns a new comparator with a second sorting rule. The second rule is only used when the first rule finds two objects equal (when it returns 0).
For example, sort cars by brand, and when two cars have the same brand, sort them by year.
Tip: You can call thenComparing() more than once, to add a third or a fourth rule.
Syntax
One of the following:
public Comparator<T> thenComparing(Comparator<? super T> other)
public <U extends Comparable<? super U>> Comparator<T> thenComparing(Function<? super T, ? extends U> keyExtractor)
public <U> Comparator<T> thenComparing(Function<? super T, ? extends U> keyExtractor, Comparator<? super U> keyComparator)
T refers to the data type of the objects to sort, for example Car. U refers to the data type of the key (the value that is compared), for example String.
Parameter Values
| Parameter | Description |
|---|---|
| other | A comparator to use when the first comparator finds two objects equal. Use either other or keyExtractor. |
| keyExtractor | A Function or lambda expression that returns the value to sort by when the first comparator finds two objects equal, for example c -> c.year. |
| keyComparator | Optional. A comparator that compares the keys from keyExtractor. If it is left out, the keys are compared in their natural order. |
Technical Details
| Returns: | A Comparator that uses this comparator first, and the second rule when two objects are equal. |
|---|
Related Pages
Java Advanced Sorting Tutorial
Java Lambda Expressions Tutorial
❮ Comparator Methods