Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

List.sort()

Sorts a list in place using a given rule.

Available since: Java 8

Syntax

default void sort(Comparator<? super E> c)

Parameters

ParameterTypeDescription
cComparator<? super E>The comparison rule; `null` means the natural order of the elements.

Examples

Ascending and descending:

void main() {
    List<Integer> nums = new ArrayList<>(List.of(5, 2, 9, 1));
    nums.sort(null);
    IO.println(nums);
    nums.sort(Comparator.reverseOrder());
    IO.println(nums);
}

Output:

[1, 2, 5, 9]
[9, 5, 2, 1]

Strings by length, then alphabetically:

void main() {
    List<String> words = new ArrayList<>(List.of("pear", "fig", "apple", "kiwi"));
    words.sort(Comparator.comparing(String::length).thenComparing(Comparator.naturalOrder()));
    IO.println(words);
}

Output:

[fig, kiwi, pear, apple]

Notes

The sort is stable: equal elements keep their original order. The method changes the list itself, so an unmodifiable List.of() throws UnsupportedOperationException. To get a sorted copy use stream().sorted().toList().

See also

Related recipes

In the tutorial

  • Sorting and comparators — Sorting collections in Java: natural order, reverse order, the Comparable interface, Comparator.comparing and sorting by several fields.

Thanks for reading!

Donate to the site — we work hard for you.