Java Reference ยท Collections
Java List.sort() method
Reference for Java List.sort(): sort a list in place with natural order or a Comparator, stability, null handling, immutable lists and Collections.sort().
List.sort(Comparator) sorts a list in place (since Java 8). Pass a comparator to define the order, or null to use the natural order of the elements, which then must implement Comparable. The sort is stable: elements that compare as equal keep their relative order.
Collections.sort(list) does the same job and simply calls list.sort(null). The List.sort() form is preferred in modern code, especially with Comparator.comparing(...) chains. To get a sorted copy instead of changing the original, copy the list first or use a stream.
names.sort(null); // natural order people.sort(Comparator.comparing(Person::age));
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Syntax
default void sort(Comparator<? super E> c)
| Name | Description |
|---|---|
c |
The ordering. null means natural ordering via Comparable. |
Returns: nothing (void); the list itself is reordered.
Throws: UnsupportedOperationException if the list cannot be modified (List.of()); ClassCastException if elements are not mutually comparable; NullPointerException when natural order meets a null; IllegalArgumentException (possibly) when a comparator breaks its contract.
Usage notes
- Algorithm: a stable merge sort variant (TimSort) with
O(n log n)worst case and nearlyO(n)on data that is already sorted. - Stable: sort by a secondary key first, then by the primary key, or chain with
thenComparing(). - Comparator contract: keep it consistent; subtracting ints (
a - b) can overflow, useInteger.compare(a, b). nulls: wrap withComparator.nullsFirst()ornullsLast().- Fixed-size lists:
Arrays.asList(...)can be sorted (it writes through to the array);List.of()cannot. - Sorted copy:
new ArrayList<>(list)thensort, orlist.stream().sorted().toList(). - Sets and maps: sets have no
sort(); useTreeSetor sort a list of the elements. - Binary search (
Collections.binarySearch) only works on lists sorted with the same comparator.