Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

Comparator.comparing()

Creates a comparator that compares objects by one key.

Available since: Java 8

Syntax

static <T, U extends Comparable<? super U>> Comparator<T> comparing(Function<? super T, ? extends U> keyExtractor)

Parameters

ParameterTypeDescription
keyExtractorFunction<T, U>A function that extracts the sort key, usually a method reference such as Person::age.

Return value

Comparator<T>A comparator for sort(), min(), max(), TreeMap.

Examples

Sorting by age and by name:

record Person(String name, int age) {}
 
void main() {
    var people = new ArrayList<>(List.of(
            new Person("Oleg", 35), new Person("Anna", 28), new Person("Maria", 31)));
    people.sort(Comparator.comparing(Person::age));
    IO.println(people);
    people.sort(Comparator.comparing(Person::name));
    IO.println(people);
}

Output:

[Person[name=Anna, age=28], Person[name=Maria, age=31], Person[name=Oleg, age=35]]
[Person[name=Anna, age=28], Person[name=Maria, age=31], Person[name=Oleg, age=35]]

A comparator in max(), and comparingInt() for numbers:

record Person(String name, int age) {}
 
void main() {
    var people = List.of(new Person("Oleg", 35), new Person("Anna", 28));
    var oldest = people.stream().max(Comparator.comparingInt(Person::age)).get();
    IO.println(oldest.name());
}

Output:

Oleg

Notes

For primitive keys there are comparingInt(), comparingLong(), comparingDouble() — they avoid boxing. If the key may be null, wrap the comparison: comparing(Person::city, Comparator.nullsLast(Comparator.naturalOrder())).

See also

  • Comparator.thenComparing() — Adds a second sort criterion — for objects equal by the first one.
  • Comparator.reversed() — Returns a comparator with the opposite order. For the natural order there is Comparator.reverseOrder().
  • Comparable.compareTo() — Defines the natural order of a class — used by sort() and TreeSet.
  • Arrays.sort() — Sorts an array in place — in ascending order or by a given comparator.
  • List.sort() — Sorts a list in place using a given rule.

Related recipes

In the tutorial

  • Sorting and comparators — Sorting collections in Java: natural order, reverse order, the Comparable interface, Comparator.comparing and sorting by several fields.

Thanks for reading!

Donate to the site — we work hard for you.