Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Comparator.thenComparingInt(): add a secondary int sort key

Add an ascending `int` key to an existing comparator. The numeric key determines the order only when the existing comparator returns `0`.

Version: Java SE 21

Syntax

default Comparator<T> thenComparingInt(ToIntFunction<? super T> keyExtractor)

Comparator.thenComparingInt() is a default method on java.util.Comparator, available since Java 8. It returns a composed comparator. If the existing comparator returns a nonzero result, that result determines the order. Only when it returns 0 does the new comparator compare the int keys in ascending order. Equal keys produce 0, which does not mean the objects are equal according to equals().

The argument, ToIntFunction<? super T>, can take a T or a supertype of T as its input type and returns a primitive int. Pass a method reference such as Task::priority or a lambda such as task -> task.priority(). Unlike thenComparing with a Comparable key extractor, this method does not require boxing the key as an Integer.

Use the static Comparator.comparingInt(...) method when the numeric key is your first criterion. Use thenComparingInt(...) on an existing comparator when the number should only break ties. Passing null as the key extractor throws NullPointerException.

Examples

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

public class Main {
    record Task(String team, int priority) {}

    public static void main(String[] args) {
        var tasks = new ArrayList<>(List.of(
                new Task("Ops", 3),
                new Task("Dev", 4),
                new Task("Ops", 1),
                new Task("Dev", 2)
        ));

        Comparator<Task> order = Comparator.comparing(Task::team)
                .thenComparingInt(Task::priority);

        tasks.sort(order);
        for (Task task : tasks) {
            System.out.println(task.team() + " " + task.priority());
        }
    }
}

Result

Dev 2
Dev 4
Ops 1
Ops 3

The team name is compared first, and priority increases only within the same team. That is why `Dev 4` comes before `Ops 1` even though `4` is greater than `1`.

Related lessons

  • Java · Lesson 61 · Basic · Version: 2

Sources