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
| Parameter | Type | Description |
|---|---|---|
| list | List<T> | The modifiable list to sort. |
| c | Comparator<? 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
- List.sort() — Sorts a list in place using a given rule.
- Comparator.comparing() — Creates a comparator that compares objects by one key.
- Collections.reverse() — Reverses the order of list elements in place.
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.