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.CollectionsArraysListCollectionMap
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
| Methods | Since | Best for |
|---|---|---|
sortbinarySearchreverseshuffleminmax | Java 1.2 | Ordering and searching lists |
rotateswapfillcopynCopies | Java 1.2 to 1.4 | Rearranging and initializing lists |
frequencydisjointaddAll | Java 5 | Counting, overlap checks, bulk adds |
unmodifiableXxxsynchronizedXxx | Java 1.2 | Read-only and locked views |
checkedXxx | Java 5 | Catching wrong types from legacy code |
newSetFromMapasLifoQueue | Java 6 | Sets and stacks with custom behaviour |
unmodifiableSequencedCollection | Java 21 | Read-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)Collections.sort
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.
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:
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]
sorts in natural order. It is stable, so equal elements keep their relative order, and it delegates toCollections.sort , which forList.sort sorts the internal array directly. Sorting is covered in depth on theArrayListsorting page . found 19 at index 2. For a missing value it returnsbinarySearch : 50 gave -5, so it belongs at index 4, and inserting it there keeps the list sorted.-(insertion point) - 1- 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
was passed.reverseOrder() moves every element two places to the right, wrapping around, and a negative distance moves them back.rotate(list, 2) exchanges two positions.swap
Counting, filling and copying
The word list contains a duplicate so that frequency
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:
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
andmin use natural order or a comparator; the longest word was found withmax . On an empty collection both throwComparator.comparing(String::length) .NoSuchElementException counts elements equal to the argument, andfrequency is true when two collections have nothing in common. Both scan the whole collection.disjoint 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 withnCopies(3, "-") a pre-filled mutable list.new ArrayList<>(nCopies(n, 0)) with a seededshuffle gives the same order every run, which is what tests need.Random overwrites the first elements of the destination and leaves the rest, and it throwscopy when the destination is shorter than the source. It never grows the destination; to copy into a new list, useIndexOutOfBoundsException .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.
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:
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}
returns a read-only view: adding through it throws, but changes made to the source show through, so the view sawunmodifiableList .c returns an immutable snapshot that never changes. The difference is explained on theList.copyOfimmutable collections page .- Wrapping a view that is already unmodifiable returns the same object, so repeated wrapping does not stack up layers.
locks the list on every method call, but a loop is many calls. Iterating without holding the list's lock can throwsynchronizedList if another thread changes it, so the loop is wrapped inConcurrentModificationException . For most concurrent code, the classes on thesynchronized (shared)concurrent collections page are a better fit.- Generics are checked only by the compiler, so legacy code with raw types can put an
into aInteger . The error then appears far away, as aList<String> when the element is read. AClassCastException checks the type at insertion, which points at the code that caused the problem.checkedList ,emptyList andsingletonList return small immutable collections.singletonMap- 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.
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:
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
adds several values to any collection in one call.addAll(collection, elements...) turns any map into a set with that map's behaviour. Backed by anewSetFromMap it gives a thread-safe set, the same asConcurrentHashMap . Backed by anConcurrentHashMap.newKeySet() it compares withIdentityHashMap , so two equal but distinct strings count as 2 elements.== presents aasLifoQueue as a last-in, first-outDeque , for code that expects aQueue but needs stack order: 3 came out first.Queue reverses any comparator, here sorting by length, longest first.reverseOrder(comparator)- Java 21 added
,unmodifiableSequencedCollection andunmodifiableSequencedSet , which keepunmodifiableSequencedMap andgetFirst available on the read-only view, and areversed overload that accepts anyshuffle .RandomGenerator - The empty collections are shared singletons, so
and returning them costs no allocation.emptyList() == emptyList()
What searching costs
containsbinarySearch
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):
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)
scans up to a million elements per lookup and took hundreds of milliseconds for 1,000 lookups.list.contains ,frequency andindexOf on lists have the same linear cost.disjoint 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.binarySearch- A
was faster still, but it costs memory for the hash table and gives no ordering. If the data is sorted anyway,HashSet is often good enough.binarySearch - Sorting a million shuffled
objects took a few hundred milliseconds, so sorting once and then searching many times pays off quickly.Integer
Which helper to use
| Task | Use |
|---|---|
| Sort a list | list.sort(cmp)Collections.sort(list) |
| Find a value in a sorted list | Collections.binarySearch |
| Largest or smallest element | Collections.maxmin |
| Count one value | Collections.frequency |
| List of n identical values | Collections.nCopies(n, value) |
| Repeatable shuffle | Collections.shuffle(list, new Random(seed)) |
| Read-only view of a changing collection | Collections.unmodifiableList |
| Fixed snapshot | List.copyOf |
| Catch wrong types from legacy code | Collections.checkedList |
| Thread-safe set | ConcurrentHashMap.newKeySet()newSetFromMap |
| Set that compares with == | newSetFromMap(new IdentityHashMap<>()) |