Java Reference ยท Collections
Java Collections.sort() method
Reference for Java Collections.sort(): sort a mutable list by natural order or with a Comparator, stability, complexity and the List.sort alternative.
Collections.sort() sorts a List in place. With one argument it uses the elements' natural order (they must implement Comparable); with a second argument it uses the Comparator you supply. The sort is stable: elements that compare as equal keep their original relative order.
Since Java 8, list.sort(comparator) does the same job and is usually preferred. In fact, Collections.sort(list, c) just calls list.sort(c).
Collections.sort(names); Collections.sort(names, Comparator.comparing(String::length));
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
public static <T extends Comparable<? super T>> void sort(List<T> list) public static <T> void sort(List<T> list, Comparator<? super T> c)
| Name | Description |
|---|---|
list |
The list to sort in place. Must support set (an ArrayList does). |
c |
The comparator. If null, natural ordering is used. |
Returns: nothing (void); the list itself is modified.
Throws: UnsupportedOperationException if the list is read-only (for example from List.of); ClassCastException if elements are not mutually comparable; NullPointerException when natural ordering meets a null; IllegalArgumentException (possibly) if the comparator breaks its contract.
Usage notes
- Algorithm: a stable merge sort variant (TimSort).
O(n log n)worst case, close toO(n)on data that is already mostly sorted. - Stable sort makes multi-key sorting possible by sorting twice, but a chained comparator (
thenComparing) is cleaner. - Works on any
List, includingLinkedList, by copying to an array, sorting, and writing back. - Prefer
list.sort(...)in new code. It avoids the static call and has the same behavior. Collections.sortreturnsvoid. A common mistake islist = Collections.sort(list), which does not compile.- Case: natural
Stringorder is by UTF-16 code unit, so"Zebra"comes before"apple". UseString.CASE_INSENSITIVE_ORDERor ajava.text.Collatorfor human-friendly order. - Sets and maps cannot be sorted in place. Use
TreeSet,TreeMapor copy to a list first. - Streams:
stream.sorted()returns a new sorted stream instead of mutating a source.