Collections.sort
Collections.sort orders the elements of a list in place. It uses TimSort, which is stable and runs in O(n log n) in the worst case.
Detailed Explanation
Sorting is the operation you reach for most often after "put it in a list". Java gives you a correct, tuned, well-tested sort, and writing your own is almost never the right call outside of an exercise.
There are two ways to tell the library what "ordered" means. The first is natural ordering: the element type implements Comparable and defines compareTo. String, Integer, LocalDate and enums all do. Calling Collections.sort(list) on a list of those works with no extra arguments. Pass a list of a type that does not implement Comparable and you get a ClassCastException at runtime, not a compile error, because erasure removes the type information the call would need.
The second is a Comparator, an object that compares two elements. Since Java 8 you build these declaratively with Comparator.comparing, comparingInt, thenComparing and reversed, which reads far better than a hand-written compare method and is harder to get wrong.
Modern Java prefers list.sort(comparator) over Collections.sort(list, comparator). List.sort was added as a default method in Java 8, and Collections.sort now delegates straight to it. The two-argument static call still exists and still works; the instance method is the idiomatic one, and TreeSet or TreeMap may be a better answer if you need the data sorted all the time rather than once.
The algorithm matters when you reason about behaviour. Collections.sort and Arrays.sort(Object[]) use TimSort, an adaptive merge sort. It is stable: elements that compare equal keep their original relative order, which is what makes multi-pass sorting work. It detects runs that are already ordered, so nearly-sorted input approaches O(n). It needs up to O(n) temporary space for merging.
Arrays.sort on a primitive array is a different algorithm entirely: dual-pivot quicksort, which sorts in place with O(log n) stack and no merge buffer. Stability is meaningless for primitives because equal int values are indistinguishable. Since JDK 14 it falls back to heapsort when recursion goes too deep, so the classic quadratic worst case is no longer reachable.
You reach for sorting as a preprocessing step constantly: before binary search, before the two-pointer technique, before greedy interval scheduling, before grouping duplicates. Sorting first costs O(n log n) and usually dominates the total runtime of those solutions.
The cost to remember: Collections.sort mutates the list. If the list is immutable, such as one from List.of or Collectors.toUnmodifiableList, the call throws UnsupportedOperationException. When you need a sorted copy, use list.stream().sorted(cmp).toList() instead.
Code Examples
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class SortEmployees {
record Employee(String name, String team, int salary) {}
public static void main(String[] args) {
// List.of returns an immutable list, so copy it before sorting in place.
List<Employee> staff = new ArrayList<>(List.of(
new Employee("Asha", "platform", 120_000),
new Employee("Ben", "search", 95_000),
new Employee("Chen", "platform", 120_000),
new Employee("Dia", "search", 140_000)));
Comparator<Employee> byTeam = Comparator.comparing(Employee::team);
// comparingInt avoids boxing every salary into an Integer during the sort.
Comparator<Employee> bySalaryDesc = Comparator.comparingInt(Employee::salary).reversed();
Comparator<Employee> byName = Comparator.comparing(Employee::name);
staff.sort(byTeam.thenComparing(bySalaryDesc).thenComparing(byName));
staff.forEach(e -> System.out.println(e.name()));
// prints: Asha
// prints: Chen
// prints: Dia
// prints: Ben
}
}import java.util.Arrays;
public class SortAlgorithms {
public static void main(String[] args) {
int[] primitives = {5, 3, 9, 1};
Arrays.sort(primitives); // dual-pivot quicksort: in place, stability not applicable
System.out.println(Arrays.toString(primitives)); // prints: [1, 3, 5, 9]
Integer[] boxed = {5, 3, 9, 1};
Arrays.sort(boxed); // TimSort: stable, uses a temporary merge buffer
System.out.println(Arrays.toString(boxed)); // prints: [1, 3, 5, 9]
// Why (a, b) -> a - b is a broken comparator: the subtraction overflows.
System.out.println(Integer.MIN_VALUE - 1); // prints: 2147483647
// A positive result means "a is greater", so MIN_VALUE would sort after 1.
}
}Common Gotchas
Sorting an immutable list throws
`List.of(...)`, `Collections.unmodifiableList` and `Stream.toList` all produce lists that reject `sort`, `set` and `add` with `UnsupportedOperationException`. Copy into an `ArrayList` first, or sort in the stream.
An inconsistent comparator throws mid-sort
TimSort verifies its assumptions and raises `IllegalArgumentException: Comparison method violates its general contract!`. The usual causes are a comparator that is not transitive, one that returns `0` for elements it later treats as different, or values mutating while the sort runs.
Never compare ints by subtracting them
`(a, b) -> a.value - b.value` overflows when the operands are far apart and silently produces the wrong order. Use `Integer.compare(a, b)` or `Comparator.comparingInt`.
Stability is what makes multi-key sorting work
sorting by salary and then by team gives the right answer only because TimSort preserves the earlier order within each team. `Arrays.sort` on primitives gives no such guarantee, and neither does `Stream.sorted` on a parallel stream with an unstable source.