CKTIS / Java
Collections.sort — sorting a list in Java
Sort an existing list by its elements’ natural order or by a comparator. Both overloads modify the same list and preserve the relative order of elements that compare as equal.
Version: Java SE 21
Syntax
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
// Collections method signatures:
public static <T extends Comparable<? super T>> void sort(List<T> list)
public static <T> void sort(List<T> list, Comparator<? super T> c)
// Call forms:
Collections.sort(list);
Collections.sort(list, comparator);Collections.sort is a static method of java.util.Collections that reorders the elements of the supplied List. Its return type is void: it does not return a new list. Collections.sort() is shorthand for referring to the method, not a valid zero-argument call. Both overloads require a list.
Collections.sort(list) sorts in ascending natural order, as defined by Comparable.compareTo. The elements must be comparable to one another. Collections.sort(list, comparator) uses the order defined by a Comparator that can compare every pair of elements. With a non-null comparator, the elements do not have to implement Comparable. A null comparator selects natural ordering. In Java SE 21, both overloads delegate to List.sort.
Both overloads are stable: elements whose comparison returns 0 keep their relative order, even if equals considers them different. The list must allow element replacement, but its size need not be changeable. Do not rely on sorting a list from List.of(...): it can throw UnsupportedOperationException. To preserve the original order, sort new ArrayList<>(list) instead.
A null list throws NullPointerException. Elements that cannot be compared under the chosen ordering can cause ClassCastException. If the implementation detects a violation of the Comparable or Comparator contract, it may throw IllegalArgumentException; detection is not guaranteed.
Examples
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class CollectionsSortDemo {
public static void main(String[] args) {
List<Integer> numbers = new ArrayList<>(List.of(3, 1, 2));
Collections.sort(numbers);
System.out.println(numbers);
List<String> names = new ArrayList<>(List.of("Zoe", "Mia", "Bo", "Al"));
Collections.sort(names, Comparator.comparingInt(String::length));
System.out.println(names);
}
}Result
[1, 2, 3] [Bo, Al, Zoe, Mia]
The first call sorts the integers in ascending order. The second uses `Comparator.comparingInt(String::length)` to sort strings from shortest to longest. Among strings of the same length, `Bo` stays before `Al`, and `Zoe` stays before `Mia`.
Related lessons
- Java · Lesson 33 · Advanced · Version: 2
- Java · Lesson 48 · Basic · Version: 2
- Java · Lesson 65 · Basic · Version: 2
- Java · Lesson 5 · Intermediate · Version: 2