The Collections Utility Class

java.util.Collections is a class of static helper methods that work on any collection: sorting and searching, counting, filling and reordering, and wrappers that make a collection read-only, thread-safe or type-checked. This page explains what each group does, shows the traps in binarySearch, copy and the wrappers, covers the lesser-known methods, and measures search costs.

Contents

What the Collections class is

java.util.Collections, added with the collections framework in Java 1.2, is not a collection itself. It is a class of static methods that operate on collections or return them, in the same way Arrays holds helpers for arrays. Most methods work through the List, Collection or Map interfaces, so they work with any implementation.

The methods fall into a few groups:

  • Algorithms that read or reorder a list: sort, binarySearch, reverse, shuffle, rotate, swap, min, max, frequency.
  • Wrappers that return a view of an existing collection with different behaviour: unmodifiableXxx, synchronizedXxx, checkedXxx.
  • Factories for small special collections: emptyList, singletonList, nCopies, newSetFromMap.
Collections methods by group
MethodsSinceBest for
sort, binarySearch, reverse, shuffle, min, maxJava 1.2Ordering and searching lists
rotate, swap, fill, copy, nCopiesJava 1.2 to 1.4Rearranging and initializing lists
frequency, disjoint, addAllJava 5Counting, overlap checks, bulk adds
unmodifiableXxx, synchronizedXxxJava 1.2Read-only and locked views
checkedXxxJava 5Catching wrong types from legacy code
newSetFromMap, asLifoQueueJava 6Sets and stacks with custom behaviour
unmodifiableSequencedCollection and friendsJava 21Read-only views of sequenced collections

Several methods return views rather than copies. A view stores only a reference to the original collection and translates every call, so creating one costs almost nothing, and the view always reflects the current contents of the original. That is useful, but it also means a view is only as read-only or as thread-safe as the code that still holds the original reference. Keep that in mind for every wrapper on this page.

Since Java 8 some of these have instance equivalents, such as list.sort(cmp), which Collections.sort now simply calls. The programs ran on JDK 21.

Sorting, binary search and reordering

A short list of scores with a duplicate shows the search rules, including what happens when a value is missing and when the list is not sorted at all.

Java
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class SortAndSearch {

    public static void main(String[] args) {
        List<Integer> scores = new ArrayList<>(List.of(42, 7, 19, 88, 7, 63));

        Collections.sort(scores);                       // natural order, stable
        System.out.println("sorted:        " + scores);

        // binarySearch needs a list sorted in the same order
        System.out.println("search 19:     " + Collections.binarySearch(scores, 19));
        int missing = Collections.binarySearch(scores, 50);
        System.out.println("search 50:     " + missing + "  -> insert at " + (-missing - 1));
        scores.add(-missing - 1, 50);
        System.out.println("inserted 50:   " + scores + " (still sorted)");
        System.out.println("search 7:      " + Collections.binarySearch(scores, 7)
            + " (either duplicate may be found)");

        // On an unsorted list the result is undefined
        List<Integer> unsorted = List.of(42, 7, 19, 88, 63);
        System.out.println("unsorted, search 42: " + Collections.binarySearch(unsorted, 42)
            + " although 42 is at index 0");

        Collections.reverse(scores);
        System.out.println("reversed:      " + scores);
        Collections.sort(scores, Comparator.reverseOrder()); // same as scores.sort(...)
        System.out.println("descending:    " + scores);
        System.out.println("search 19 with the same comparator: "
            + Collections.binarySearch(scores, 19, Comparator.reverseOrder()));

        Collections.rotate(scores, 2);                  // move every element 2 places right
        System.out.println("rotate by 2:   " + scores);
        Collections.rotate(scores, -2);
        System.out.println("rotate by -2:  " + scores);
        Collections.swap(scores, 0, scores.size() - 1);
        System.out.println("swap ends:     " + scores);
    }
}

Output:

Output
sorted:        [7, 7, 19, 42, 63, 88]
search 19:     2
search 50:     -5  -> insert at 4
inserted 50:   [7, 7, 19, 42, 50, 63, 88] (still sorted)
search 7:      1 (either duplicate may be found)
unsorted, search 42: -4 although 42 is at index 0
reversed:      [88, 63, 50, 42, 19, 7, 7]
descending:    [88, 63, 50, 42, 19, 7, 7]
search 19 with the same comparator: 4
rotate by 2:   [7, 7, 88, 63, 50, 42, 19]
rotate by -2:  [88, 63, 50, 42, 19, 7, 7]
swap ends:     [7, 63, 50, 42, 19, 7, 88]
  • Collections.sort sorts in natural order. It is stable, so equal elements keep their relative order, and it delegates to List.sort, which for ArrayList sorts the internal array directly. Sorting is covered in depth on the sorting page.
  • binarySearch found 19 at index 2. For a missing value it returns -(insertion point) - 1: 50 gave -5, so it belongs at index 4, and inserting it there keeps the list sorted.
  • With duplicates, it returns the index of one of them, not necessarily the first: 7 was found at index 1.
  • On an unsorted list the result is undefined. Searching for 42, which is at index 0, returned -4. No exception warns about it.
  • A list sorted with a comparator must be searched with the same comparator; the descending list found 19 at index 4 only when reverseOrder() was passed.
  • rotate(list, 2) moves every element two places to the right, wrapping around, and a negative distance moves them back. swap exchanges two positions.

Counting, filling and copying

The word list contains a duplicate so that frequency has something to count, and the copy examples include a destination that is too small.

Java
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Random;

public class CountAndFill {

    public static void main(String[] args) {
        List<String> words = List.of("pear", "fig", "apple", "fig", "banana");

        System.out.println("min:            " + Collections.min(words));
        String longest = Collections.max(words, Comparator.comparing(String::length));
        System.out.println("max by length:  " + longest);
        System.out.println("frequency fig:  " + Collections.frequency(words, "fig"));
        boolean noOverlap = Collections.disjoint(words, List.of("kiwi", "plum"));
        System.out.println("disjoint:       " + noOverlap);

        // nCopies: an immutable list of n identical elements, no array of n is created
        List<String> blanks = Collections.nCopies(3, "-");
        System.out.println("nCopies:        " + blanks);

        // A shuffle with a fixed seed is repeatable, which is what tests need
        List<Integer> deck = new ArrayList<>(List.of(1, 2, 3, 4, 5, 6));
        Collections.shuffle(deck, new Random(42));
        System.out.println("shuffle(seed):  " + deck);

        Collections.fill(deck, 0);
        System.out.println("fill:           " + deck);

        // copy needs a destination at least as large as the source
        List<Integer> target = new ArrayList<>(List.of(9, 9, 9, 9, 9, 9, 9));
        Collections.copy(target, List.of(1, 2, 3));
        System.out.println("copy:           " + target);
        try {
            Collections.copy(new ArrayList<>(), List.of(1, 2, 3));
        } catch (IndexOutOfBoundsException e) {
            System.out.println("copy to empty:  IndexOutOfBoundsException");
        }
    }
}

Output:

Output
min:            apple
max by length:  banana
frequency fig:  2
disjoint:       true
nCopies:        [-, -, -]
shuffle(seed):  [2, 1, 5, 6, 4, 3]
fill:           [0, 0, 0, 0, 0, 0]
copy:           [1, 2, 3, 9, 9, 9, 9]
copy to empty:  IndexOutOfBoundsException
  • min and max use natural order or a comparator; the longest word was found with Comparator.comparing(String::length). On an empty collection both throw NoSuchElementException.
  • frequency counts elements equal to the argument, and disjoint is true when two collections have nothing in common. Both scan the whole collection.
  • nCopies(3, "-") returns an immutable list that stores the element once and reports a size of 3. It is a cheap way to create a list of identical values, or with new ArrayList<>(nCopies(n, 0)) a pre-filled mutable list.
  • shuffle with a seeded Random gives the same order every run, which is what tests need.
  • copy overwrites the first elements of the destination and leaves the rest, and it throws IndexOutOfBoundsException when the destination is shorter than the source. It never grows the destination; to copy into a new list, use new ArrayList<>(source).

Wrappers: unmodifiable, synchronized and checked

A wrapper is a thin object that forwards calls to the collection inside it, changing some of them. The program creates each kind and shows the behaviour that most often surprises people.

Java
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Wrappers {

    public static void main(String[] args) {
        List<String> source = new ArrayList<>(List.of("a", "b"));

        // unmodifiableList is a read-only VIEW: it reflects later changes to the source
        List<String> view = Collections.unmodifiableList(source);
        // List.copyOf is a read-only SNAPSHOT: later changes do not show
        List<String> snapshot = List.copyOf(source);
        source.add("c");
        System.out.println("view:     " + view);
        System.out.println("snapshot: " + snapshot);
        try {
            view.add("d");
        } catch (UnsupportedOperationException e) {
            System.out.println("view.add: UnsupportedOperationException");
        }
        System.out.println("wrapping twice returns the same view: "
            + (Collections.unmodifiableList(view) == view));

        // synchronizedList locks each call, but iteration needs your own lock
        List<Integer> shared = Collections.synchronizedList(new ArrayList<>());
        shared.add(1);
        shared.add(2);
        int sum = 0;
        synchronized (shared) {            // without this, another thread could modify mid-loop
            for (int n : shared) {
                sum += n;
            }
        }
        System.out.println("sum:      " + sum);

        // checkedList catches wrong types when they are inserted, not when they are read
        List<String> names = new ArrayList<>();
        addRaw(names);
        System.out.println("unchecked list now holds: " + names);
        try {
            String first = names.get(0);
            System.out.println(first);
        } catch (ClassCastException e) {
            System.out.println("reading it later: ClassCastException");
        }
        try {
            addRaw(Collections.checkedList(new ArrayList<>(), String.class));
        } catch (ClassCastException e) {
            System.out.println("checkedList: ClassCastException at insertion");
        }

        // Small immutable helpers
        System.out.println("empty:    " + Collections.emptyList() + ", single: "
            + Collections.singletonList("only") + ", map: " + Collections.singletonMap("k", 1));
    }

    // Simulates legacy code that ignores generics
    @SuppressWarnings({"rawtypes", "unchecked"})
    static void addRaw(List list) {
        list.add(42);
    }
}

Output:

Output
view:     [a, b, c]
snapshot: [a, b]
view.add: UnsupportedOperationException
wrapping twice returns the same view: true
sum:      3
unchecked list now holds: [42]
reading it later: ClassCastException
checkedList: ClassCastException at insertion
empty:    [], single: [only], map: {k=1}
  • unmodifiableList returns a read-only view: adding through it throws, but changes made to the source show through, so the view saw c. List.copyOf returns an immutable snapshot that never changes. The difference is explained on the immutable collections page.
  • Wrapping a view that is already unmodifiable returns the same object, so repeated wrapping does not stack up layers.
  • synchronizedList locks the list on every method call, but a loop is many calls. Iterating without holding the list's lock can throw ConcurrentModificationException if another thread changes it, so the loop is wrapped in synchronized (shared). For most concurrent code, the classes on the concurrent collections page are a better fit.
  • Generics are checked only by the compiler, so legacy code with raw types can put an Integer into a List<String>. The error then appears far away, as a ClassCastException when the element is read. A checkedList checks the type at insertion, which points at the code that caused the problem.
  • emptyList, singletonList and singletonMap return small immutable collections.
  • Read-only is shallow: an unmodifiable list of mutable objects still lets callers change those objects. Only the list structure, which elements it holds and in what order, is protected.

Less known but useful methods

A few methods solve problems that otherwise need a custom class. The program uses each on a tiny example, including two methods added in Java 21.

Java
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.IdentityHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Queue;
import java.util.Set;
import java.util.SequencedCollection;
import java.util.concurrent.ConcurrentHashMap;
import java.util.random.RandomGenerator;

public class LessKnown {

    public static void main(String[] args) {
        // addAll with varargs: add several elements to any collection
        List<String> list = new ArrayList<>();
        Collections.addAll(list, "c", "a", "b");
        System.out.println("addAll:           " + list);

        // newSetFromMap: a Set with the behaviour of any Map
        Set<String> concurrentSet = Collections.newSetFromMap(new ConcurrentHashMap<>());
        concurrentSet.add("x");
        Set<String> identitySet = Collections.newSetFromMap(new IdentityHashMap<>());
        identitySet.add(new String("same"));
        identitySet.add(new String("same"));
        System.out.println("concurrent set:   " + concurrentSet + ", identity set size: "
            + identitySet.size());

        // asLifoQueue: a Deque viewed as a stack-ordered Queue
        Queue<Integer> stack = Collections.asLifoQueue(new java.util.ArrayDeque<>());
        stack.add(1);
        stack.add(2);
        stack.add(3);
        System.out.println("asLifoQueue poll: " + stack.poll() + " " + stack.poll());

        // reverseOrder of a comparator
        Comparator<String> byLength = Comparator.comparingInt(String::length);
        list.add("long");
        list.sort(Collections.reverseOrder(byLength));
        System.out.println("reverseOrder(byLength): " + list);

        // Java 21: unmodifiable sequenced views and shuffle with any RandomGenerator
        SequencedCollection<String> seq = Collections.unmodifiableSequencedCollection(
            new LinkedHashSet<>(List.of("one", "two", "three")));
        System.out.println("sequenced view:   first=" + seq.getFirst() + ", reversed="
            + seq.reversed());
        List<Integer> deck = new ArrayList<>(List.of(1, 2, 3, 4, 5, 6));
        Collections.shuffle(deck, RandomGenerator.of("L64X128MixRandom"));
        System.out.println("shuffled size:    " + deck.size() + " (order varies per run)");

        // emptyIterator and other shared empty instances
        System.out.println("emptyIterator:    " + Collections.emptyIterator().hasNext()
            + ", emptyList() == emptyList(): "
            + (Collections.emptyList() == Collections.emptyList()));
    }
}

Output:

Output
addAll:           [c, a, b]
concurrent set:   [x], identity set size: 2
asLifoQueue poll: 3 2
reverseOrder(byLength): [long, c, a, b]
sequenced view:   first=one, reversed=[three, two, one]
shuffled size:    6 (order varies per run)
emptyIterator:    false, emptyList() == emptyList(): true
  • addAll(collection, elements...) adds several values to any collection in one call.
  • newSetFromMap turns any map into a set with that map's behaviour. Backed by a ConcurrentHashMap it gives a thread-safe set, the same as ConcurrentHashMap.newKeySet(). Backed by an IdentityHashMap it compares with ==, so two equal but distinct strings count as 2 elements.
  • asLifoQueue presents a Deque as a last-in, first-out Queue, for code that expects a Queue but needs stack order: 3 came out first.
  • reverseOrder(comparator) reverses any comparator, here sorting by length, longest first.
  • Java 21 added unmodifiableSequencedCollection, unmodifiableSequencedSet and unmodifiableSequencedMap, which keep getFirst and reversed available on the read-only view, and a shuffle overload that accepts any RandomGenerator.
  • The empty collections are shared singletons, so emptyList() == emptyList() and returning them costs no allocation.

What searching costs

contains, binarySearch and a hash lookup answer the same question with very different costs. The program runs 1,000 lookups against a million sorted integers with each, keeping the fastest of three runs.

Java
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.function.IntPredicate;

public class UtilitySpeed {

    public static void main(String[] args) {
        int n = 1000000;
        List<Integer> sorted = new ArrayList<>(n);
        for (int i = 0; i < n; i++) {
            sorted.add(i * 2);
        }
        Set<Integer> set = new HashSet<>(sorted);
        Random random = new Random(5);
        int[] probes = new int[1000];
        for (int i = 0; i < probes.length; i++) {
            probes[i] = random.nextInt(2 * n);
        }
        System.out.printf("1,000 lookups in %,d sorted integers:%n", n);
        time("list.contains (linear)", probes, x -> sorted.contains(x));
        time("Collections.binarySearch", probes, x -> Collections.binarySearch(sorted, x) >= 0);
        time("HashSet.contains", probes, x -> set.contains(x));

        List<Integer> shuffled = new ArrayList<>(sorted);
        Collections.shuffle(shuffled, new Random(1));
        long t0 = System.nanoTime();
        Collections.sort(shuffled);
        System.out.printf("Collections.sort of %,d shuffled Integers: %.0f ms (one run)%n", n,
            (System.nanoTime() - t0) / 1e6);
    }

    // Best of 3 runs
    static void time(String name, int[] probes, IntPredicate lookup) {
        long best = Long.MAX_VALUE;
        int found = 0;
        for (int run = 0; run < 3; run++) {
            found = 0;
            long t0 = System.nanoTime();
            for (int p : probes) {
                if (lookup.test(p)) {
                    found++;
                }
            }
            best = Math.min(best, System.nanoTime() - t0);
        }
        System.out.printf("  %-26s %9.3f ms  found %d%n", name, best / 1e6, found);
    }
}

Output (rough timings, 2-CPU Linux machine, JDK 21):

Output
1,000 lookups in 1,000,000 sorted integers:
  list.contains (linear)       696.121 ms  found 510
  Collections.binarySearch       0.576 ms  found 510
  HashSet.contains               0.098 ms  found 510
Collections.sort of 1,000,000 shuffled Integers: 324 ms (one run)
  • list.contains scans up to a million elements per lookup and took hundreds of milliseconds for 1,000 lookups. frequency, indexOf and disjoint on lists have the same linear cost.
  • binarySearch needs about 20 comparisons per lookup on a million elements and was more than a thousand times faster. It only works on a list that is sorted and supports fast index access.
  • A HashSet was faster still, but it costs memory for the hash table and gives no ordering. If the data is sorted anyway, binarySearch is often good enough.
  • Sorting a million shuffled Integer objects took a few hundred milliseconds, so sorting once and then searching many times pays off quickly.

Which helper to use

Choosing a Collections method
TaskUse
Sort a listlist.sort(cmp) or Collections.sort(list)
Find a value in a sorted listCollections.binarySearch, with the sort's comparator
Largest or smallest elementCollections.max or min, with a comparator if needed
Count one valueCollections.frequency
List of n identical valuesCollections.nCopies(n, value)
Repeatable shuffleCollections.shuffle(list, new Random(seed))
Read-only view of a changing collectionCollections.unmodifiableList
Fixed snapshotList.copyOf
Catch wrong types from legacy codeCollections.checkedList
Thread-safe setConcurrentHashMap.newKeySet() or newSetFromMap
Set that compares with ==newSetFromMap(new IdentityHashMap<>())