Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Comparator.thenComparingLong — breaking ties with a long key

Comparator.thenComparingLong adds an ascending long key, used only when the preceding comparator reports a tie.

Version: Java SE 21; repository runtime, production runtime not attested

Syntax

default Comparator<T> thenComparingLong(ToLongFunction<? super T> keyExtractor)

Comparator.thenComparingLong returns a composed comparator. Only when the preceding comparator returns 0 does it compare long keys in ascending order. A tie means comparison equality, not necessarily equals.

keyExtractor has type ToLongFunction<? super T> and returns a primitive long. The default implementation is equivalent to thenComparing(comparingLong(keyExtractor)). Unlike comparingLong, this method appends a criterion to an existing comparator.

A null argument causes NullPointerException. Calling reversed() on the entire chain reverses every criterion, not just the last.

The example orders by group, then id: consequently, B:1 stays after the A items.

Examples

import java.util.Arrays;
import java.util.Comparator;

public class Main {
    record Item(String group, long id) {}

    public static void main(String[] args) {
        Item[] items = {
            new Item("B", 1L),
            new Item("A", 3000000000L),
            new Item("A", 2L)
        };

        Comparator<Item> order = Comparator.comparing(Item::group)
                .thenComparingLong(Item::id);
        Arrays.sort(items, order);

        for (Item item : items) {
            System.out.println(item.group() + ":" + item.id());
        }
    }
}

Result

A:2
A:3000000000
B:1

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources