Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Comparator: descending priority, then ascending sequence number

Sort tasks by highest priority first and break ties with the smallest sequence number. See where `reversed()` belongs and how to supply the explicit `<Task>` type argument.

Version: Java SE 21

Syntax

Comparator<Task> order = Comparator.<Task>comparingInt(Task::priority)
    .reversed()
    .thenComparingLong(Task::seq);

The Comparator.comparingInt/reversed/thenComparingLong chain combines three methods from java.util.Comparator. The static generic method comparingInt takes a ToIntFunction<? super T> and builds a comparator that orders by an int key in ascending order. In Comparator.<Task>comparingInt(Task::priority), the explicit type argument <Task>, also called a type witness, fixes T to Task at that call. It is optional when the compiler can infer the type.

The default method reversed() returns a comparator with the opposite ordering. Call it before adding the second key so that only priority is reversed. Moving that call to the end would reverse a comparator that orders both keys ascending, making both priority and seq descending.

The default method thenComparingLong takes a ToLongFunction<? super T> and compares the long key in ascending order only when the preceding comparator returns 0. The int and long keys need no boxing into Integer or Long. If both keys tie, the comparison returns 0; that does not require equals to return true.

Examples

import java.util.Comparator;
import java.util.stream.Stream;

public class Main {
    record Task(String name, int priority, long seq) {}

    public static void main(String[] args) {
        Comparator<Task> order = Comparator.<Task>comparingInt(Task::priority)
            .reversed()
            .thenComparingLong(Task::seq);

        Stream.of(
                new Task("low", 1, 1L),
                new Task("later", 5, 3_000_000_002L),
                new Task("earlier", 5, 3_000_000_001L))
            .sorted(order)
            .map(Task::name)
            .forEachOrdered(System.out::println);
    }
}

Result

earlier
later
low

`forEachOrdered` prints the names in sorted order. `earlier` comes before `later` because its `seq` is smaller; `low` comes last despite having the smallest `seq` because its priority is lower.

Related lessons

  • Java · Lesson 38 · Advanced · Version: 2

Sources