Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

Collections.sort()

Sorts a list in place.

Available since: Java 1.2

Syntax

static <T extends Comparable<? super T>> void sort(List<T> list)
static <T> void sort(List<T> list, Comparator<? super T> c)

Parameters

ParameterTypeDescription
listList<T>The modifiable list to sort.
cComparator<? super T>Optional comparison rule.

Examples

Natural order and order by a rule:

void main() {
    List<String> names = new ArrayList<>(List.of("Oleg", "anna", "Ivan"));
    Collections.sort(names);
    IO.println(names);
    Collections.sort(names, String.CASE_INSENSITIVE_ORDER);
    IO.println(names);
}

Output:

[Ivan, Oleg, anna]
[anna, Ivan, Oleg]

Notes

Since Java 8 list.sort(comparator) does the same and is more common in new code. Strings sort by character codes, so capital letters come before lowercase ones. Elements that are not Comparable need a comparator, otherwise the code does not compile.

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.