Java Comparator comparing() Method
Example
Sort a list of cars by brand:
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) {
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(Comparator.comparing(c -> c.brand));
System.out.println(myCars);
}
}
Definition and Usage
The comparing() method creates a comparator that sorts objects by one of their values, called the key. You give it a lambda expression that takes an object and returns the key, for example c -> c.brand for the brand of a car.
The keys are compared in their natural order: strings alphabetically and numbers from small to large. To compare the keys in another way, give a comparator for the keys as the second argument.
Tip: To sort by an int value, like a year, you can also use comparingInt().
Syntax
One of the following:
public static <T, U extends Comparable<? super U>> Comparator<T> comparing(Function<? super T, ? extends U> keyExtractor)
public static <T, U> Comparator<T> comparing(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 |
|---|---|
| keyExtractor | Required. A Function or lambda expression that takes an object and returns the value to sort by, for example c -> c.brand. |
| keyComparator | Optional. A comparator that compares the keys. If it is left out, the keys are compared in their natural order. |
Technical Details
| Returns: | A Comparator that compares objects by the key. |
|---|
Related Pages
Java Advanced Sorting Tutorial
Java Lambda Expressions Tutorial
❮ Comparator Methods