Skip to content
Tutorials Center
My learning

Topics

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).

Java
Collections.sort(names);
Collections.sort(names, Comparator.comparing(String::length));

Try it

Java Natural order and comparators

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.

Java Stability and failure modes

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

Java
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 to O(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, including LinkedList, 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.sort returns void. A common mistake is list = Collections.sort(list), which does not compile.
  • Case: natural String order is by UTF-16 code unit, so "Zebra" comes before "apple". Use String.CASE_INSENSITIVE_ORDER or a java.text.Collator for human-friendly order.
  • Sets and maps cannot be sorted in place. Use TreeSet, TreeMap or copy to a list first.
  • Streams: stream.sorted() returns a new sorted stream instead of mutating a source.