Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Comparator — composing ordering rules

java.util.Comparator describes an ordering independently of the objects' class. It lets you combine keys, reverse direction, and handle null explicitly for both whole elements and their fields.

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

Syntax

Comparator<T> order = Comparator.comparing(keyExtractor, keyComparator).thenComparingInt(intKeyExtractor);
Comparator<T> descending = order.reversed();
Comparator<T> nullable = Comparator.nullsLast(order);

java.util.Comparator<T> defines an ordering: compare(a, b) returns a negative value, zero, or a positive value. The comparison must be transitive. Swapping the arguments must change the sign of a nonzero result; if compare(a, b) returns zero, compare(b, a) must also return zero. If compare(a, b) returns zero, then for every z, compare(a, z) and compare(b, z) must return results with the same sign: both negative, both zero, or both positive. Zero means equivalent in this ordering, not necessarily equals; in TreeSet and TreeMap this affects uniqueness.

Comparator.comparing compares extracted keys using their natural ordering or a supplied comparator. Comparator.naturalOrder uses Comparable and rejects null. Comparator.comparingInt uses an int key without boxing to Integer.

Comparator.thenComparing adds a tie-breaker used only on ties; it accepts a comparator or a key extractor, optionally with a key comparator. Comparator.thenComparingInt adds an int key. Comparator.reversed reverses the entire ordering built so far, so call placement matters.

Comparator.nullsFirst and Comparator.nullsLast place null before or after non-null values, respectively. Wrapping the key comparator protects the key; wrapping the whole ordering protects the element. Reversing a wrapped comparator also reverses the position of null.

Examples

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

public class Main {
    record Item(String name, int score, int id) {}

    public static void main(String[] args) {
        Item[] items = {
            new Item("Ada", 10, 2),
            null,
            new Item(null, 10, 4),
            new Item("Ada", 10, 1),
            new Item("Bob", 20, 3)
        };

        Comparator<Item> byName = Comparator.comparing(
                Item::name,
                Comparator.nullsFirst(Comparator.<String>naturalOrder()));
        Comparator<Item> order = Comparator.comparingInt(Item::score)
                .reversed()
                .thenComparing(byName)
                .thenComparingInt(Item::id);

        Arrays.sort(items, Comparator.nullsLast(order));
        for (Item item : items) {
            System.out.println(item == null ? "null"
                    : item.name() + ":" + item.score() + ":" + item.id());
        }
    }
}

Result

Bob:20:3
null:10:4
Ada:10:1
Ada:10:2
null

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