CKTIS / Java
List.sort — stable list sorting
List.sort reorders an existing list using a comparator or natural ordering while preserving the relative order of elements that compare as equal.
Version: Java SE 21; repository runtime, production runtime not attested
Syntax
default void sort(Comparator<? super E> c)
list.sort(comparator);
list.sort(null);List.sort sorts the existing list and returns void, not a new list. The Comparator<? super E> argument determines ordering; null selects natural ordering, requiring mutually comparable elements implementing Comparable.
Sorting is stable: elements for which the comparator returns zero retain their relative order. In the example, pear, kiwi, and plum remain in that order after sorting by length.
The list must support replacing elements, but need not support resizing. List.of(...) is unmodifiable; create a copy using new ArrayList<>(...) before sorting. Unsupported modification causes UnsupportedOperationException.
All elements must be mutually comparable under the selected ordering; otherwise, ClassCastException can occur.
Examples
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> words = new ArrayList<>(List.of("pear", "fig", "kiwi", "plum"));
words.sort(Comparator.comparingInt(String::length));
System.out.println(words);
words.sort(null);
System.out.println(words);
}
}Result
[fig, pear, kiwi, plum] [fig, kiwi, pear, plum]
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.