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, Arrays.sort(Object[]) and stream sorted(), 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.
  • Primitive arrays, in Arrays.sort(int[]) 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.

ArrayList.sort sorts its internal array directly. Other lists are copied to an array, sorted and written back. Sets and maps cannot be sorted in place at all; they are either kept sorted by a tree, or copied into a list and sorted.

Sorting APIs
APISinceSortsBest for
list.sort(cmp)Java 8A list in place; null means natural orderMost list sorting
Collections.sort(list)Java 1.2The same; calls list.sortOlder code
Arrays.sort(array), Arrays.sort(a, from, to)Java 1.2An array or part of oneArrays, primitive data
Arrays.parallelSortJava 8Large arrays on several coresMillions of elements, many CPUs
stream().sorted(cmp)Java 8A new sorted sequencePipelines; keeping the source unchanged
TreeSet, TreeMapJava 1.2Always sorted on insertData that changes and must stay sorted

Comparators themselves are covered on Comparable and Comparator. Every program here was compiled and run with JDK 21.

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.

Java
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:

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 Fig first, because uppercase letters have smaller character codes than lowercase. String.CASE_INSENSITIVE_ORDER fixes that.
  • Chained comparators sort by length and then by reverse alphabetical order within the same length.
  • comparingInt(City::population) sorts records by a field; stream().sorted() returns a new sorted list and leaves the source alone.
  • Arrays.sort(int[]) sorts primitives in ascending order. A descending order with Comparator.reverseOrder() needs boxed Integer[].

Arrays, ranges, nulls and floating point

Several details of Arrays.sort are easy to miss: partial sorting, descending primitives, special double values, nulls, and the views and immutable lists that sorting interacts with.

Java
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:

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
  • Arrays.sort(a, 2, 5) sorted only indexes 2 to 4, leaving the rest in place.
  • There is no comparator overload for int[]. Sorting ascending and reversing in place avoids boxing a large array.
  • double arrays sort by Double.compare: -0.0 comes before 0.0, and NaN goes last, although == treats the zeros as equal and NaN as unequal to everything.
  • Natural order throws NullPointerException on a null element; Comparator.nullsFirst or nullsLast places nulls explicitly.
  • Sorting an Arrays.asList view sorts the array underneath it.
  • List.of lists cannot be sorted in place, and sort throws UnsupportedOperationException; sort a copy.

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.

Java
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:

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 TreeSet keeps its elements sorted at all times, and a TreeMap its keys.
  • Sorting a map by value means sorting its entries: stream the entrySet, sort with comparingByValue, and collect into a LinkedHashMap to keep that order. blue and green both have 12 and kept their key order thanks to the stable sort.
  • 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 Integers are sorted twice to show TimSort's shortcut for ordered input.

Java
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):

Output
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 ints are sorted as a primitive array, in parallel, as a list of Integer, and as a stream, keeping the fastest of three runs, each on a fresh copy.

Java
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):

Output
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 int[] was several times faster than sorting the same values as a List<Integer>. Primitive comparisons are cheap and the data is contiguous, while each Integer is a separate object reached through a reference.
  • parallelSort 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.
  • The stream version cost about the same as sorting the list, plus building the result.
  • Sorting an already sorted int[] was more than ten times faster than sorting random data, because the JDK's DualPivotQuicksort first tries to find and merge already ordered runs (the tryMergeRuns step in the JDK 21 source) before falling back to quicksort.

Sorting text for people: Collator and natural order

String.compareTo compares UTF-16 code units, which is fast and consistent but not how people expect words to be ordered: all capital letters come before all lower-case ones, and accented letters come after "z". File names with numbers have a similar problem, because "file10" sorts before "file2". The program sorts a list of words with accents and mixed case, and a list of numbered file names, both ways.

Java
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:

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 compareTo, "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).
  • java.text.Collator sorts by the rules of a language: Collator.getInstance(Locale.FRENCH) put the words in dictionary order, with "éclair" and "Émile" among the "e" words. Collator implements Comparator<Object>, so it can be passed straight to sort. Use it for anything shown to users: names, titles, menu entries.
  • A collator's strength decides which differences count. At PRIMARY strength, only base letters matter, so "resume" and "Résumé" compare as equal, which is useful for search and de-duplication.
  • 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 TreeSet and TreeMap.
  • Collation is slower than compareTo. When sorting many strings with the same collator, Collator.getCollationKey precomputes a key per string so each comparison is cheap.

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.

Java
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:

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]]
  • (a, b) -> a - b is a common shortcut, and it is wrong for values far apart: Integer.MAX_VALUE - Integer.MIN_VALUE 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::compare, or Comparator.comparingInt, never overflows.
  • 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 IllegalArgumentException: Comparison method violates its general contract!. Real-world causes include comparing mutable fields that change during the sort, mixing up NaN with < and >, and comparators that treat null inconsistently. The exception only appears when the sort happens to notice, usually with larger inputs, so it can show up first in production.
  • 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 TreeSet or TreeMap one of them would be lost, because sorted collections treat compare == 0 as "same element". Add tie-breakers with thenComparing until the order is total. See Comparable and Comparator for the full contract.

Which approach to use

Choosing how to sort
SituationUse
Sort a mutable listlist.sort(comparator)
Keep the original, get a sorted liststream().sorted(cmp).toList()
Numbers, large volumesArrays.sort(int[]) on a primitive array
Very large arrays, many coresArrays.parallelSort
Data that must stay sorted while changingTreeSet or TreeMap
A map ordered by valueSort the entries, collect into a LinkedHashMap
Nulls in the dataComparator.nullsFirst or nullsLast
Multi-key ordercomparing(...).thenComparing(...), or stable sorts in sequence
Only the top few elementsA small heap; see PriorityQueue