Sub topic 8
Sorting lists, arrays and streams
This chapter assumes you know how to write a Comparable class, how to build a Comparator with lambdas and factory methods, and how List and arrays work. Here you will apply those orderings with the sorting APIs the JDK provides. You will see what each API mutates, which orderings it accepts, and how it fails.
The four entry points
Java has four common ways to sort. They differ in what they sort and whether they change the original data.
| API | Sorts | Changes the original? | Ordering |
|---|---|---|---|
| `Collections.sort(list)` | a `List` | yes, in place | natural order only |
| `Collections.sort(list, cmp)` | a `List` | yes, in place | comparator |
| `list.sort(cmp)` | a `List` | yes, in place | comparator, or natural order if `cmp` is `null` |
| `Arrays.sort(array)` and `Arrays.sort(array, cmp)` | an array | yes, in place | natural order or comparator |
| `stream.sorted()` and `stream.sorted(cmp)` | a stream | no, it produces a new stream | natural order or comparator |
Sorting lists
Collections.sort and List.sort do the same work. Collections.sort(list, cmp) simply calls list.sort(cmp). Prefer list.sort in new code, because it reads left to right and accepts null to mean natural order.
The program below is complete. It defines a small Person record with the same natural ordering by age as the earlier chapter.
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class ListSortDemo {
record Person(String name, int age) implements Comparable<Person> {
@Override
public int compareTo(Person other) {
return Integer.compare(age, other.age);
}
}
public static void main(String[] args) {
List<Person> people = new ArrayList<>(List.of(
new Person("Ana", 31), new Person("Bo", 25), new Person("Cy", 31)));
Collections.sort(people);
System.out.println(people); // Bo, Ana, Cy
people.sort(Comparator.comparing(Person::name).reversed());
System.out.println(people); // Cy, Bo, Ana
people.sort(null); // null means natural order
System.out.println(people); // Bo, Ana, Cy
}
}Ana and Cy are both 31. After Collections.sort(people), Ana still comes before Cy, because the list sort is stable. A stable sort keeps elements that compare as equal in their original relative order. Stability is guaranteed for object sorting, and it makes multi-pass sorting possible: sort by the secondary key first, then by the primary key, and the secondary order survives within ties. In practice thenComparing is clearer, but you will meet the multi-pass style in older code.
How the sort works inside
For object lists and arrays, the JDK uses TimSort, a merge-sort variant. It runs in O(n log n) time in the worst case and runs faster on data that is already partly ordered. ArrayList.sort copies nothing extra beyond what the algorithm needs: it sorts its internal array directly. The default List.sort for other lists copies the elements into an array, sorts that, and writes them back through the list iterator. For a LinkedList this is faster than sorting nodes in place.
Lists that cannot be sorted
Sorting writes to the list, so the list must allow writes.
import java.util.Arrays;
import java.util.List;
public class ImmutableSortDemo {
public static void main(String[] args) {
List<Integer> fixed = Arrays.asList(3, 1, 2);
fixed.sort(null); // works: the list is fixed-size but writable
System.out.println(fixed); // [1, 2, 3]
List<Integer> immutable = List.of(3, 1, 2);
try {
immutable.sort(null);
} catch (UnsupportedOperationException e) {
System.out.println("List.of lists cannot be sorted");
}
List<Integer> sortedCopy = immutable.stream().sorted().toList();
System.out.println(sortedCopy); // [1, 2, 3]
}
}Arrays.asList returns a view of the array. Sorting that list also reorders the original array. List.of, Stream.toList() and Collections.unmodifiableList views all reject sort with UnsupportedOperationException. When you must keep the original, copy first with new ArrayList<>(source) and sort the copy.
Sorting arrays
Arrays.sort has separate overloads for each primitive type and a generic overload for objects. They use different algorithms.
- Primitive arrays (
int[],double[]and so on) use a dual-pivot quicksort. Stability is irrelevant because equal primitives are indistinguishable. - Object arrays (
T[]) use TimSort and are stable.
import java.util.Arrays;
import java.util.Comparator;
public class ArraySortDemo {
public static void main(String[] args) {
int[] nums = {5, 2, 9, 1, 7};
Arrays.sort(nums);
System.out.println(Arrays.toString(nums)); // [1, 2, 5, 7, 9]
int[] part = {9, 8, 7, 6, 5};
Arrays.sort(part, 1, 4); // sorts indexes 1 to 3; the end index is exclusive
System.out.println(Arrays.toString(part)); // [9, 6, 7, 8, 5]
Integer[] boxed = {5, 2, 9, 1, 7};
Arrays.sort(boxed, Comparator.reverseOrder());
System.out.println(Arrays.toString(boxed)); // [9, 7, 5, 2, 1]
String[] names = {"bo", "Ana", "cy"};
Arrays.sort(names, String.CASE_INSENSITIVE_ORDER);
System.out.println(Arrays.toString(names)); // [Ana, bo, cy]
}
}Three details matter here.
- Primitive arrays take no comparator.
Arrays.sort(int[], Comparator)does not exist. To sort anint[]in descending order, sort ascending and reverse the array, or box it into anInteger[]first. - Range sorts use an exclusive end index.
Arrays.sort(a, from, to)throwsIllegalArgumentExceptioniffrom > to, andArrayIndexOutOfBoundsExceptionif the range leaves the array. - Floating-point sorting has a defined total order.
Arrays.sort(double[])places-0.0before0.0and puts everyNaNlast. This differs from the<operator, which treats-0.0and0.0as equal andNaNas unordered.
Sorting streams
Stream.sorted() is an intermediate operation. It does not change the source collection. It returns a new stream whose elements are in order.
import java.util.Comparator;
import java.util.List;
public class StreamSortDemo {
record Person(String name, int age) {}
public static void main(String[] args) {
List<Person> people = List.of(
new Person("Ana", 31), new Person("Bo", 25), new Person("Cy", 31));
List<String> names = people.stream()
.sorted(Comparator.comparingInt(Person::age)
.reversed()
.thenComparing(Person::name))
.map(Person::name)
.toList();
System.out.println(names); // [Ana, Cy, Bo]
System.out.println(people.get(0).name()); // Ana: the source list is untouched
}
}Note the difference from the list examples. This Person record does not implement Comparable, so calling sorted() with no argument on Stream<Person> would compile but fail at run time.
What sorted() does at run time
- It is a barrier.
sortedis a stateful operation. It must read every upstream element before it can emit the first one. On an infinite stream, such asStream.iterate(1, n -> n + 1).sorted(), it never finishes. Putlimitorfilterbeforesortedwhen you can, so less data gets buffered. - It is stable for ordered streams. A stream from a
Listor an array is ordered, so equal elements keep their encounter order. A stream from aHashSethas no defined encounter order, so there is no order to preserve. - It stays correct in parallel. For ordered streams,
parallelStream().sorted()gives the same result as the sequential version, including stability. - Short-circuiting does not skip the sort.
stream.sorted().findFirst()still sorts everything. If you only need the smallest element, usemin(comparator), which is O(n).
Failures you will see
| Symptom | Cause | Fix |
|---|---|---|
| `ClassCastException` naming your class and `Comparable` | You called a natural-order sort on elements that do not implement `Comparable` | Pass a comparator, or implement `Comparable` |
| `NullPointerException` inside `compareTo` or the comparator | The data contains `null`, and the ordering does not handle it | Wrap the ordering in `Comparator.nullsFirst` or `nullsLast` |
| `UnsupportedOperationException` | The list is immutable | Sort a copy, or use `stream().sorted().toList()` |
| `IllegalArgumentException: Comparison method violates its general contract!` | A comparator that breaks the compare contract, often found by TimSort on larger inputs | Fix the comparator (see the contract chapter) |
The last failure is intermittent. TimSort only detects a broken contract when its merge steps happen to hit an inconsistent comparison. A small test list can pass while a production-sized list throws. A comparator that works on three elements is not proven correct.
Choosing between the APIs
- Use
list.sort(cmp)when you own a mutable list and want it ordered from now on. - Use
Arrays.sortfor arrays, with a boxed array when you need a comparator. - Use
stream().sorted(cmp)when the sort is one step in a pipeline, or when the source must not change. - Use
Collections.sort(list)mainly when maintaining older code. It adds nothing overlist.sort(null)and only accepts natural order or a comparator.
Exercise
A method receives List<String> names, which may come from List.of(...). It must return the names sorted case-insensitively, and must not change the argument. Which code is correct, and why do names.sort(String.CASE_INSENSITIVE_ORDER) and Collections.sort(names) both fail the requirements?
Show answer
Return names.stream().sorted(String.CASE_INSENSITIVE_ORDER).toList();, or copy first with List<String> copy = new ArrayList<>(names); copy.sort(String.CASE_INSENSITIVE_ORDER); return copy;. names.sort(...) changes the argument, which breaks the requirement, and it throws UnsupportedOperationException when the list is immutable. Collections.sort(names) has the same two problems, and it also uses case-sensitive natural order, so it would put "Zed" before "ana".
Exercise
You have int[] scores = {40, 90, 70} and need it in descending order. Arrays.sort(scores, Comparator.reverseOrder()) does not compile. Give two working approaches.
Show answer
Primitive arrays have no comparator overload. First approach: call Arrays.sort(scores), then reverse the array in place with a loop that swaps scores[i] and scores[scores.length - 1 - i]. Second approach: box it with Integer[] boxed = Arrays.stream(scores).boxed().toArray(Integer[]::new); and call Arrays.sort(boxed, Comparator.reverseOrder());.