Skip to content
Tutorials Center
My learning

Topics

Java Reference ยท Collections

Java Comparator.comparing()

Reference for Comparator.comparing(), comparingInt() and thenComparing(): build multi-field sort orders from key extractors and method references.

Comparator.comparing() builds a comparator from a key extractor: a function that picks the value to sort by. Instead of writing (a, b) -> a.name().compareTo(b.name()) you write Comparator.comparing(Person::name). Chain more keys with thenComparing() and flip the order with reversed() or with a second argument.

The static factories come in boxed and primitive flavors: comparing, comparingInt, comparingLong and comparingDouble. The primitive ones avoid creating wrapper objects for every comparison.

Java
people.sort(Comparator.comparing(Person::city)
        .thenComparingInt(Person::age)
        .thenComparing(Person::name));

Try it

Java Sorting by several fields

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Java Key comparators, nulls and stream usage

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Syntax

Java
static <T,U extends Comparable<? super U>> Comparator<T> comparing(Function<? super T,? extends U> keyExtractor)
static <T,U> Comparator<T> comparing(Function<? super T,? extends U> keyExtractor, Comparator<? super U> keyComparator)
static <T> Comparator<T> comparingInt(ToIntFunction<? super T> keyExtractor)
static <T> Comparator<T> comparingLong(ToLongFunction<? super T> keyExtractor)
static <T> Comparator<T> comparingDouble(ToDoubleFunction<? super T> keyExtractor)

default Comparator<T> thenComparing(Comparator<? super T> other)
default <U extends Comparable<? super U>> Comparator<T> thenComparing(Function<? super T,? extends U> keyExtractor)
default <U> Comparator<T> thenComparing(Function<? super T,? extends U> keyExtractor, Comparator<? super U> keyComparator)
default Comparator<T> thenComparingInt(ToIntFunction<? super T> keyExtractor)
Name Description
keyExtractor Maps an element to the value to compare.
keyComparator How to compare the extracted keys; the default is their natural order.

Returns: a new Comparator<T>. Throws: NullPointerException immediately if an argument is null; later, if an extracted key is null and no null-safe comparator is used.

Usage notes

  • Reversal with lambdas needs a type hint. Comparator.comparing(p -> p.age()).reversed() fails to compile because p is inferred as Object. Use a method reference (Person::age), an explicit type ((Person p) -> p.age()) or Collections.reverseOrder() in the two-argument form.
  • Overloaded method references can be ambiguous. thenComparing(String::toLowerCase) does not compile, because toLowerCase has an overload taking a Locale that also fits the Comparator overload. Wrap it: thenComparing(Comparator.comparing(String::toLowerCase)).
  • reversed() reverses the whole chain built so far. Put it where you want it: comparing(A).reversed().thenComparing(B) reverses only A.
  • Prefer comparingInt for int keys. comparing(Person::age) boxes each age; the primitive version does not.
  • Null keys: wrap with Comparator.nullsFirst(...) or nullsLast(...) as the key comparator.
  • Keys are extracted on every comparison. A sort of n items calls the extractor about 2 n log n times, so keep it cheap or precompute keys for expensive extractors.
  • Stable sorting: with List.sort() ties keep their previous order, so you can sort by a secondary key first, then a primary key, as an alternative to chaining.
  • Maps: Map.Entry.comparingByKey() and comparingByValue() build comparators for entries.