Sorting Collections
Java can sort a list in place, sort an array, produce a sorted stream, or keep data sorted all the time in a TreeSet or TreeMap. Behind these are two algorithms with different guarantees. This page explains which algorithm runs where, sorts lists, arrays, sets and maps with comparators, covers stability, nulls and floating-point values, and measures sorting speed.
Contents
What sorts what, and how
Java uses two sorting algorithms, chosen by the type of data:
- Objects, in
,List.sort ,Collections.sort and streamArrays.sort(Object[]) , are sorted with TimSort, a merge sort that detects runs that are already in order. It is stable: elements that compare as equal keep their original order. It is O(n log n) in the worst case and close to O(n) on data that is nearly sorted.sorted() - Primitive arrays, in
and the other primitive overloads, use a dual-pivot quicksort. Stability does not matter for primitives, since equal values are indistinguishable, and this algorithm avoids the extra memory of merge sort.Arrays.sort(int[])
ArrayList.sort
| API | Since | Sorts | Best for |
|---|---|---|---|
list.sort(cmp) | Java 8 | A list in place; null | Most list sorting |
Collections.sort(list) | Java 1.2 | The same; calls list.sort | Older code |
Arrays.sort(array)Arrays.sort(a, from, to) | Java 1.2 | An array or part of one | Arrays, primitive data |
Arrays.parallelSort | Java 8 | Large arrays on several cores | Millions of elements, many CPUs |
stream().sorted(cmp) | Java 8 | A new sorted sequence | Pipelines; keeping the source unchanged |
TreeSetTreeMap | Java 1.2 | Always sorted on insert | Data that changes and must stay sorted |
Comparators themselves are covered on
Sorting lists and arrays with comparators
Fruit names in mixed case show the difference between natural and case-insensitive order, and city records are sorted by a numeric property.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
public class SortLists {
record City(String name, int population) {
}
public static void main(String[] args) {
List<String> words = new ArrayList<>(List.of("pear", "apple", "Fig", "kiwi", "banana"));
words.sort(null); // null = natural order
System.out.println("natural: " + words);
words.sort(String.CASE_INSENSITIVE_ORDER);
System.out.println("case-insensitive: " + words);
Comparator<String> byLength = Comparator.comparing(String::length);
words.sort(byLength.thenComparing(Comparator.reverseOrder()));
System.out.println("length, then Z-A: " + words);
List<City> cities = new ArrayList<>(List.of(
new City("Lagos", 15400000), new City("Lima", 10900000),
new City("Oslo", 710000), new City("Delhi", 33800000)));
cities.sort(Comparator.comparingInt(City::population).reversed());
System.out.println("by population: " + cities.stream().map(City::name).toList());
// Sorted copy, original untouched
List<String> unsorted = List.of("c", "a", "b");
List<String> sortedCopy = unsorted.stream().sorted().toList();
System.out.println("stream sorted: " + sortedCopy);
// Arrays
int[] nums = {5, 3, 9, 1};
Arrays.sort(nums);
System.out.println("int[]: " + Arrays.toString(nums));
Integer[] boxed = {5, 3, 9, 1};
Arrays.sort(boxed, Comparator.reverseOrder()); // primitives cannot take a comparator
System.out.println("Integer[] desc: " + Arrays.toString(boxed));
}
}
Output:
natural: [Fig, apple, banana, kiwi, pear]
case-insensitive: [apple, banana, Fig, kiwi, pear]
length, then Z-A: [Fig, pear, kiwi, apple, banana]
by population: [Delhi, Lagos, Lima, Oslo]
stream sorted: [a, b, c]
int[]: [1, 3, 5, 9]
Integer[] desc: [9, 5, 3, 1]
- Natural order puts
first, because uppercase letters have smaller character codes than lowercase.Fig fixes that.String.CASE_INSENSITIVE_ORDER - Chained comparators sort by length and then by reverse alphabetical order within the same length.
sorts records by a field;comparingInt(City::population) returns a new sorted list and leaves the source alone.stream().sorted() sorts primitives in ascending order. A descending order withArrays.sort(int[]) needs boxedComparator.reverseOrder() .Integer[]
Arrays, ranges, nulls and floating point
Several details of Arrays.sort
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.ArrayList;
public class ArraysDetails {
public static void main(String[] args) {
// Sort only part of an array: [from, to)
int[] a = {9, 8, 7, 6, 5, 4, 3};
Arrays.sort(a, 2, 5);
System.out.println("sort(a, 2, 5): " + Arrays.toString(a));
// Primitive arrays have no comparator overload: box them, or sort then reverse
int[] nums = {3, 1, 2};
Arrays.sort(nums);
for (int i = 0, j = nums.length - 1; i < j; i++, j--) {
int t = nums[i];
nums[i] = nums[j];
nums[j] = t;
}
System.out.println("int[] descending: " + Arrays.toString(nums));
// Doubles: -0.0 before 0.0, NaN last (Double.compare order)
double[] d = {0.0, Double.NaN, -0.0, -1.5, 2.5};
Arrays.sort(d);
System.out.println("double[] sorted: " + Arrays.toString(d));
// Objects with nulls: natural order throws, nullsFirst works
String[] withNull = {"b", null, "a"};
try {
Arrays.sort(withNull);
} catch (NullPointerException e) {
System.out.println("sort with null: NullPointerException");
}
Arrays.sort(withNull, Comparator.nullsFirst(Comparator.naturalOrder()));
System.out.println("nullsFirst: " + Arrays.toString(withNull));
// A list view sorts the array underneath
Integer[] boxed = {5, 3, 9};
List<Integer> view = Arrays.asList(boxed);
view.sort(null);
System.out.println("Arrays.asList view sorted, array is now " + Arrays.toString(boxed));
// Sorting a copy keeps the original
List<String> original = List.of("pear", "fig", "apple");
List<String> copy = new ArrayList<>(original);
copy.sort(null);
System.out.println("original " + original + ", sorted copy " + copy);
try {
original.sort(null);
} catch (UnsupportedOperationException e) {
System.out.println("List.of(...).sort: UnsupportedOperationException");
}
}
}
Output:
sort(a, 2, 5): [9, 8, 5, 6, 7, 4, 3]
int[] descending: [3, 2, 1]
double[] sorted: [-1.5, -0.0, 0.0, 2.5, NaN]
sort with null: NullPointerException
nullsFirst: [null, a, b]
Arrays.asList view sorted, array is now [3, 5, 9]
original [pear, fig, apple], sorted copy [apple, fig, pear]
List.of(...).sort: UnsupportedOperationException
sorted only indexes 2 to 4, leaving the rest in place.Arrays.sort(a, 2, 5)- There is no comparator overload for
. Sorting ascending and reversing in place avoids boxing a large array.int[] arrays sort bydouble :Double.compare comes before-0.0 , and0.0 goes last, althoughNaN treats the zeros as equal and== as unequal to everything.NaN- Natural order throws
on a null element;NullPointerException orComparator.nullsFirst places nulls explicitly.nullsLast - Sorting an
view sorts the array underneath it.Arrays.asList lists cannot be sorted in place, andList.of throwssort ; sort a copy.UnsupportedOperationException
Sets and maps: sorted structures
A set of service names and a map of colour counts show the two options for collections that cannot be sorted in place: keep them sorted, or sort a copy of their entries.
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.TreeSet;
public class SortedStructures {
public static void main(String[] args) {
// Sets and maps cannot be sorted in place: keep them sorted, or copy
TreeSet<String> tags = new TreeSet<>(List.of("web", "api", "db"));
System.out.println("TreeSet: " + tags);
Map<String, Integer> votes = Map.of("blue", 12, "red", 30, "green", 12, "gold", 5);
Map<String, Integer> byKey = new TreeMap<>(votes);
System.out.println("map sorted by key: " + byKey);
// Sort by value: stream the entries and collect into a LinkedHashMap to keep that order
Map<String, Integer> byValue = new LinkedHashMap<>();
votes.entrySet().stream()
.sorted(Map.Entry.<String, Integer>comparingByValue(Comparator.reverseOrder())
.thenComparing(Map.Entry.comparingByKey()))
.forEach(e -> byValue.put(e.getKey(), e.getValue()));
System.out.println("map sorted by value: " + byValue);
}
}
Output:
TreeSet: [api, db, web]
map sorted by key: {blue=12, gold=5, green=12, red=30}
map sorted by value: {red=30, blue=12, green=12, gold=5}
- A
keeps its elements sorted at all times, and aTreeSet its keys.TreeMap - Sorting a map by value means sorting its entries: stream the
, sort withentrySet , and collect into acomparingByValue to keep that order.LinkedHashMap andblue both have 12 and kept their key order thanks to the stable sort.green - For data that changes often and must always be in order, a tree avoids sorting again after every change. For data sorted once and then read, a sorted list is smaller and faster to read.
Stability and already-sorted data
Race results with tied times show what stability means, and a million Integer
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Random;
public class StabilityAndCost {
record Runner(String name, int minutes) {
}
public static void main(String[] args) {
// Stable: runners with equal times keep their original (alphabetical) order
List<Runner> runners = new ArrayList<>(List.of(
new Runner("Ada", 42), new Runner("Ben", 39), new Runner("Cleo", 42),
new Runner("Dev", 39), new Runner("Eli", 45)));
runners.sort(Comparator.comparingInt(Runner::minutes));
runners.forEach(r -> System.out.println(r.minutes() + " min " + r.name()));
// Sorting a million elements
List<Integer> big = new ArrayList<>(new Random(7).ints(1000000).boxed().toList());
long start = System.nanoTime();
big.sort(null);
long first = (System.nanoTime() - start) / 1000000;
System.out.println("1,000,000 Integers sorted in " + first + " ms");
// Already sorted input: TimSort detects the run and finishes in one pass
start = System.nanoTime();
big.sort(null);
long again = (System.nanoTime() - start) / 1000000;
System.out.println("same list again (already sorted): " + again + " ms");
}
}
Output (the timings are single runs):
39 min Ben
39 min Dev
42 min Ada
42 min Cleo
45 min Eli
1,000,000 Integers sorted in 817 ms
same list again (already sorted): 24 ms
- Sorting by time kept runners with equal times in their original list order, which here was alphabetical. Stability lets you sort by a secondary key and then by the primary key, as spreadsheets do.
- Sorting the already sorted list took a few milliseconds instead of hundreds: TimSort found one long run and only checked it.
How fast is each sort?
Two million random intInteger
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.function.Supplier;
public class SortSpeed {
public static void main(String[] args) {
int n = 2000000;
int[] base = new Random(6).ints(n).toArray();
List<Integer> baseList = new ArrayList<>(n);
for (int x : base) {
baseList.add(x);
}
System.out.printf("sort %,d random values%n", n);
time("Arrays.sort(int[])", () -> {
int[] a = base.clone();
Arrays.sort(a);
return a[0];
});
time("Arrays.parallelSort(int[])", () -> {
int[] a = base.clone();
Arrays.parallelSort(a);
return a[0];
});
time("List<Integer>.sort(null)", () -> {
List<Integer> l = new ArrayList<>(baseList);
l.sort(null);
return l.get(0);
});
time("stream().sorted().toList()", () -> baseList.stream().sorted().toList().get(0));
int[] sorted = base.clone();
Arrays.sort(sorted);
time("Arrays.sort, already sorted", () -> {
int[] a = sorted.clone();
Arrays.sort(a);
return a[0];
});
}
// Best of 3 runs; each run copies the input first, and the copy is timed too
static void time(String name, Supplier<Integer> f) {
long best = Long.MAX_VALUE;
for (int run = 0; run < 3; run++) {
long t0 = System.nanoTime();
f.get();
best = Math.min(best, System.nanoTime() - t0);
}
System.out.printf(" %-30s %7.1f ms%n", name, best / 1e6);
}
}
Output (two Linux CPUs, JDK 21; the times are rough):
sort 2,000,000 random values
Arrays.sort(int[]) 128.5 ms
Arrays.parallelSort(int[]) 126.6 ms
List<Integer>.sort(null) 699.2 ms
stream().sorted().toList() 903.7 ms
Arrays.sort, already sorted 9.1 ms
- Sorting the
was several times faster than sorting the same values as aint[] . Primitive comparisons are cheap and the data is contiguous, while eachList<Integer> is a separate object reached through a reference.Integer gave little or no gain on this two-CPU machine; it splits the array across the common pool and pays off with more cores and larger arrays.parallelSort- The stream version cost about the same as sorting the list, plus building the result.
- Sorting an already sorted
was more than ten times faster than sorting random data, because the JDK'sint[] first tries to find and merge already ordered runs (theDualPivotQuicksort step in the JDK 21 source) before falling back to quicksort.tryMergeRuns
Sorting text for people: Collator and natural order
String.compareTo
import java.text.Collator;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class TextOrdering {
private static final Pattern CHUNK = Pattern.compile("\\d+|\\D+");
// "Natural" order for names with numbers: compares digit runs as numbers
static int naturalCompare(String a, String b) {
Matcher ma = CHUNK.matcher(a);
Matcher mb = CHUNK.matcher(b);
while (ma.find() && mb.find()) {
String x = ma.group();
String y = mb.group();
int c;
if (Character.isDigit(x.charAt(0)) && Character.isDigit(y.charAt(0))) {
c = Long.compare(Long.parseLong(x), Long.parseLong(y));
} else {
c = x.compareToIgnoreCase(y);
}
if (c != 0) {
return c;
}
}
return Integer.compare(a.length(), b.length());
}
public static void main(String[] args) {
List<String> names = new ArrayList<>(List.of("zebra", "Émile", "apple", "Zoë", "éclair",
"Banana"));
names.sort(null);
System.out.println("String.compareTo (code points): " + names);
Collator french = Collator.getInstance(Locale.FRENCH);
names.sort(french);
System.out.println("Collator (French): " + names);
Collator primary = Collator.getInstance(Locale.ENGLISH);
primary.setStrength(Collator.PRIMARY); // ignore accents and case
System.out.println("PRIMARY strength: \"resume\" equals \"Résumé\": "
+ (primary.compare("resume", "Résumé") == 0));
List<String> files = new ArrayList<>(List.of("file10.txt", "file2.txt", "File1.txt",
"file1.txt", "file20.txt"));
files.sort(null);
System.out.println("files, String order: " + files);
Comparator<String> natural = TextOrdering::naturalCompare;
files.sort(natural.thenComparing(Comparator.naturalOrder())); // tie-break on case
System.out.println("files, natural order: " + files);
}
}
Output:
String.compareTo (code points): [Banana, Zoë, apple, zebra, Émile, éclair]
Collator (French): [apple, Banana, éclair, Émile, zebra, Zoë]
PRIMARY strength: "resume" equals "Résumé": true
files, String order: [File1.txt, file1.txt, file10.txt, file2.txt, file20.txt]
files, natural order: [File1.txt, file1.txt, file2.txt, file10.txt, file20.txt]
- With
, "Banana" and "Zoë" came before "apple" (upper-case letters have smaller codes), and "Émile" and "éclair" ended up last (accented letters have codes above 127).compareTo sorts by the rules of a language:java.text.Collator put the words in dictionary order, with "éclair" and "Émile" among the "e" words.Collator.getInstance(Locale.FRENCH) implementsCollator , so it can be passed straight toComparator<Object> . Use it for anything shown to users: names, titles, menu entries.sort- A collator's strength decides which differences count. At
strength, only base letters matter, so "resume" and "Résumé" compare as equal, which is useful for search and de-duplication.PRIMARY - For names containing numbers, the comparator splits each string into runs of digits and non-digits and compares digit runs as numbers, so "file2" comes before "file10". File managers call this natural or "human" sort. The tie-breaker keeps the order total, so "File1.txt" and "file1.txt" are not treated as equal, which matters for
andTreeSet .TreeMap - Collation is slower than
. When sorting many strings with the same collator,compareTo precomputes a key per string so each comparison is cheap.Collator.getCollationKey
Broken comparators
A sort is only as correct as its comparator, and comparator bugs often pass tests with small or friendly data. The program shows three: a subtraction comparator that overflows, a comparator that does not give consistent answers, and one that treats different elements as equal.
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Random;
public class BrokenComparators {
public static void main(String[] args) {
// 1. Subtraction overflows for values far apart
List<Integer> values = new ArrayList<>(List.of(5, Integer.MIN_VALUE, 0, Integer.MAX_VALUE));
values.sort((a, b) -> a - b);
System.out.println("(a, b) -> a - b: " + values);
values.sort(Integer::compare);
System.out.println("Integer::compare: " + values);
// 2. A comparator that is not consistent breaks TimSort's assumptions
Random random = new Random(1);
List<Integer> big = new ArrayList<>();
for (int i = 0; i < 2000; i++) {
big.add(random.nextInt(100));
}
Comparator<Integer> moody = (a, b) -> random.nextInt(3) - 1; // -1, 0 or 1 at random
try {
Collections.sort(big, moody);
System.out.println("random comparator: no exception this time");
} catch (IllegalArgumentException e) {
System.out.println("random comparator: IllegalArgumentException: " + e.getMessage());
}
// 3. A comparator that ignores a field makes distinct elements "equal"
record Person(String name, int age) { }
List<Person> people = new ArrayList<>(List.of(new Person("Ben", 30),
new Person("Ana", 30), new Person("Cy", 25)));
people.sort(Comparator.comparingInt(Person::age));
System.out.println("by age only (stable, Ben stays before Ana): " + people);
people.sort(Comparator.comparingInt(Person::age).thenComparing(Person::name));
System.out.println("by age, then name: " + people);
}
}
Output:
(a, b) -> a - b: [0, 5, 2147483647, -2147483648]
Integer::compare: [-2147483648, 0, 5, 2147483647]
random comparator: IllegalArgumentException: Comparison method violates its general contract!
by age only (stable, Ben stays before Ana): [Person[name=Cy, age=25], Person[name=Ben, age=30], Person[name=Ana, age=30]]
by age, then name: [Person[name=Cy, age=25], Person[name=Ana, age=30], Person[name=Ben, age=30]]
is a common shortcut, and it is wrong for values far apart:(a, b) -> a - b overflows to a negative number, so the largest value was placed before the smallest one and the "sorted" list ended with the most negative number.Integer.MAX_VALUE - Integer.MIN_VALUE , orInteger::compare , never overflows.Comparator.comparingInt- A comparator must be consistent: if a < b and b < c, then a < c, and the same pair must always compare the same way. The random comparator broke this, and the JDK's merge sort (TimSort) detected it and threw
. Real-world causes include comparing mutable fields that change during the sort, mixing upIllegalArgumentException: Comparison method violates its general contract! withNaN and< , and comparators that treat> inconsistently. The exception only appears when the sort happens to notice, usually with larger inputs, so it can show up first in production.null - Comparing people only by age made Ben and Ana "equal". The sort is stable, so they kept their original order. That is harmless in a list, but in a
orTreeSet one of them would be lost, because sorted collections treatTreeMap as "same element". Add tie-breakers withcompare == 0 until the order is total. SeethenComparingComparable and Comparator for the full contract.
Which approach to use
| Situation | Use |
|---|---|
| Sort a mutable list | list.sort(comparator) |
| Keep the original, get a sorted list | stream().sorted(cmp).toList() |
| Numbers, large volumes | Arrays.sort(int[]) |
| Very large arrays, many cores | Arrays.parallelSort |
| Data that must stay sorted while changing | TreeSetTreeMap |
| A map ordered by value | Sort the entries, collect into a LinkedHashMap |
| Nulls in the data | Comparator.nullsFirstnullsLast |
| Multi-key order | comparing(...).thenComparing(...) |
| Only the top few elements | A small heap; see |