Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Comparator.comparingInt: comparing by an int key

Create a comparator that orders objects by an ascending `int` key without boxing the key as an `Integer`.

Version: Java SE 21

Syntax

static <T> Comparator<T> comparingInt(ToIntFunction<? super T> keyExtractor)

Comparator.comparingInt is a static factory method on java.util.Comparator, available since Java 8 and present in Java SE 21. Comparator.comparingInt() names the method here; it is not a valid call because there is no zero-argument overload. The method takes one key extractor (ToIntFunction<? super T>) and returns a Comparator<T>; it does not sort anything itself.

In Comparator.comparingInt(Person::age), the method reference reads the int age from each Person being compared. The comparator orders the keys numerically from smallest to largest. Unlike Comparator.comparing(Person::age), this form does not require boxing the key as an Integer.

For equal keys, compare(a, b) returns 0 even if a.equals(b) is false. The stable List.sort preserves the relative order of those elements. Use reversed() to reverse the order, or thenComparingInt(...) to break ties with a second int key.

Passing a null extractor throws NullPointerException. That is separate from a null element, which you can place last with Comparator.nullsLast(byAge). An int key cannot be null; unboxing a null Integer also throws NullPointerException. The returned comparator is serializable if the supplied extractor is serializable.

Examples

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

public class Main {
    record Person(String name, int age) {}

    public static void main(String[] args) {
        var people = new ArrayList<>(List.of(
                new Person("Mira", 30),
                new Person("Tomas", 19),
                new Person("Ada", 19)
        ));

        Comparator<Person> byAge = Comparator.comparingInt(Person::age);
        people.sort(byAge);

        for (Person person : people) {
            System.out.println(person.name() + ": " + person.age());
        }
    }
}

Result

Tomas: 19
Ada: 19
Mira: 30

`Person::age` extracts the key. `people.sort(byAge)` sorts the mutable list in place. Tomas stays ahead of Ada because both are 19 and that was their order in the input.

Related lessons

  • Java · Lesson 8 · Advanced · Version: 2
  • Java · Lesson 61 · Basic · Version: 2

Sources