Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Sorting and comparators

Sorting and comparators: List.sort and object Arrays.sort order stably by a Comparator, so elements equal under the order retain their prior encounter order.

Version: Java SE 21 (JLS and Java SE API); examples verified on the repository Java runtime

Syntax

sorting

List.sort and object Arrays.sort order stably by a Comparator, so elements equal under the order retain their prior encounter order.

Build ordering with Comparator.comparing and thenComparing, and sort a copy when the input must remain unchanged.

A comparator must be antisymmetric, transitive, and consistent; subtracting keys can overflow, and mutating a key invalidates the result.

Handle null explicitly with nullsFirst or nullsLast; empty and singleton collections remain unchanged, while natural sorting can throw ClassCastException.

Sorting by priority prints A:1,B:2,C:2; B remains before C for equal key 2, demonstrating List.sort stability.

Examples

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

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

    public static void main(String[] args) {
        List<Item> items = new ArrayList<>(List.of(new Item("B", 2), new Item("A", 1), new Item("C", 2)));
        items.sort(Comparator.comparingInt(Item::priority));
        System.out.println(items.stream().map(i -> i.name() + ":" + i.priority()).collect(Collectors.joining(",")));
    }
}

Result

A:1,B:2,C:2

Sorting by priority prints A:1,B:2,C:2; B remains before C for equal key 2, demonstrating List.sort stability.

Sources