Collections Utility in Java
The Collections utility class provides static methods for sorting, searching, shuffling, reversing, and creating unmodifiable or synchronized wrappers for collections.
java.util.Collections is a utility class (not to be confused with the Collection interface) containing only static methods that operate on or return collections. It covers the most common collection algorithms — sorting, binary search, shuffling, frequency counting — as well as factory methods for unmodifiable and synchronized wrappers. Since Java 9+, many immutable factories moved to the interfaces themselves (List.of, Set.of, Map.of), but Collections remains relevant for runtime wrapping.
Method Categories
Sorting and reordering
| Method | Description |
|---|---|
sort(List<T>) |
Sorts in natural order (Timsort, stable, O(n log n)) |
sort(List<T>, Comparator) |
Sorts with custom comparator |
reverse(List<?>) |
Reverses a list in-place |
shuffle(List<?>) |
Shuffles randomly |
shuffle(List<?>, Random) |
Shuffles with a seeded Random for deterministic results |
rotate(List<?>, int) |
Rotates elements by a given distance |
swap(List<?>, int, int) |
Swaps two elements |
fill(List<T>, T) |
Fills all elements with a single value |
copy(List<T> dest, List<T> src) |
Copies src into dest (dest must be at least as large) |
Searching
| Method | Description |
|---|---|
binarySearch(List, key) |
Binary search on sorted list (O(log n)) |
binarySearch(List, key, Comparator) |
Binary search with comparator |
min(Collection) / max(Collection) |
Returns min/max by natural order |
min(Collection, Comparator) / max(Collection, Comparator) |
With comparator |
frequency(Collection, Object) |
Counts occurrences |
disjoint(Collection, Collection) |
Returns true if no elements in common |
Unmodifiable wrappers
| Method | Description |
|---|---|
unmodifiableList(List) |
Returns read-only view |
unmodifiableSet(Set) |
Returns read-only view |
unmodifiableMap(Map) |
Returns read-only view |
unmodifiableSortedSet(SortedSet) |
Sorted variant |
unmodifiableSortedMap(SortedMap) |
Sorted variant |
Synchronized wrappers
| Method | Description |
|---|---|
synchronizedList(List) |
Thread-safe list backed by a mutex |
synchronizedSet(Set) |
Thread-safe set |
synchronizedMap(Map) |
Thread-safe map |
Singleton and empty factories
| Method | Returns |
|---|---|
emptyList() |
Immutable empty List |
emptySet() |
Immutable empty Set |
emptyMap() |
Immutable empty Map |
singletonList(T) |
Immutable List with exactly one element |
singleton(T) |
Immutable Set with exactly one element |
singletonMap(K, V) |
Immutable Map with exactly one entry |
nCopies(int, T) |
Immutable List of n copies of a value |
Examples
Sorting, reversing, and searching
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class CollectionsAlgorithms {
public static void main(String[] args) {
List<Integer> numbers = new ArrayList<>(List.of(5, 2, 8, 1, 9, 3));
Collections.sort(numbers);
System.out.println(numbers); // [1, 2, 3, 5, 8, 9]
int idx = Collections.binarySearch(numbers, 8);
System.out.println("8 found at index: " + idx); // 4
Collections.reverse(numbers);
System.out.println(numbers); // [9, 8, 5, 3, 2, 1]
System.out.println(Collections.min(numbers)); // 1
System.out.println(Collections.max(numbers)); // 9
System.out.println(Collections.frequency(List.of(1, 2, 2, 3, 2), 2)); // 3
}
}
Unmodifiable and synchronized wrappers
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
public class WrapperExamples {
public static void main(String[] args) {
// Unmodifiable wrapper — read-only view of a mutable list
List<String> mutable = new ArrayList<>(List.of("a", "b", "c"));
List<String> readOnly = Collections.unmodifiableList(mutable);
System.out.println(readOnly.get(0)); // a
// readOnly.add("d"); // throws UnsupportedOperationException
// The wrapper is a view — changes to the underlying list are visible
mutable.add("d");
System.out.println(readOnly.size()); // 4
// For a truly immutable snapshot use List.copyOf (Java 10+)
List<String> snapshot = List.copyOf(mutable);
// Synchronized wrapper for multi-threaded use (coarse-grained lock)
List<String> syncList = Collections.synchronizedList(new ArrayList<>());
// Note: iteration must still be manually synchronized:
synchronized (syncList) {
for (String s : syncList) {
System.out.println(s);
}
}
}
}
Common Mistakes
-
Using
binarySearchon an unsorted list.Collections.binarySearchrequires the list to be sorted in ascending natural order (or by the supplied comparator). Calling it on an unsorted list produces undefined results without throwing an exception. -
Trusting the unmodifiable wrapper for complete immutability.
Collections.unmodifiableList(list)returns a view. Mutations to the underlying list are still visible through the view. For a fully independent immutable copy, useList.copyOf(list)(Java 10+). -
Forgetting to synchronize iteration on synchronized wrappers.
Collections.synchronizedListwraps individual method calls with a mutex, but iteration is multiple method calls. You must still wrap iteration in asynchronizedblock:synchronized(syncList) { for (...) { ... } }. Failing to do so can result inConcurrentModificationException. -
Using
Collections.sorton a non-random-access list.Collections.sortcopies elements to an array, sorts, and copies back. This works correctly onLinkedList, but is O(n) extra space. For large linked lists, consider using a different data structure. -
Confusing
Collections.nCopieswith true distinct objects.Collections.nCopies(5, new int[]{1})returns a list of 5 references to the same array, not 5 independent arrays. Mutating one mutates all.
Best Practices
- Prefer
List.of(...),Set.of(...), andMap.of(...)(Java 9+) for creating small immutable collections — they are more concise and provide true immutability. - Use
List.copyOf(collection)(Java 10+) instead ofCollections.unmodifiableListwhen you need an immutable snapshot that is independent of the source. - For concurrent access, prefer
ConcurrentHashMapoverCollections.synchronizedMap— it offers better scalability and atomic compound operations. - Sort before calling
binarySearch— or maintain a sorted structure (TreeSet/TreeMap) from the start. - Use
Collections.emptyList(),emptySet(), andemptyMap()instead ofnew ArrayList<>()for read-only empty collections — they are singleton objects with no allocation overhead.
Interview Questions
1. What is the difference between the Collections class and the Collection interface?
Collection<E> (singular) is the root interface of the Java Collections Framework — extended by List, Set, and Queue. Collections (plural) is a utility class in java.util containing only static methods for operating on collection instances. You never instantiate Collections.
2. How does Collections.sort work internally?
Collections.sort(list) delegates to list.sort(null), which in turn calls Arrays.sort on a copy of the list's elements. Arrays.sort uses Timsort — a hybrid merge sort/insertion sort — which is stable and runs in O(n log n). The list is then updated from the sorted array.
3. What is the difference between Collections.unmodifiableList and List.copyOf?
Collections.unmodifiableList(list) returns a view backed by the original list. Structural modifications to the original are visible through the view. List.copyOf(list) (Java 10+) makes a true independent copy — it is not backed by the original, and its contents cannot be modified.
4. Why must you synchronize iteration over a synchronizedList?
Collections.synchronizedList protects individual method calls (like add, get, remove) but iteration involves repeated calls to hasNext() and next(). Another thread can structurally modify the list between these calls. Wrapping the entire iteration in a synchronized(list) block holds the lock for the whole traversal, preventing ConcurrentModificationException.
5. What does Collections.frequency do?
Collections.frequency(collection, element) counts the number of elements in the collection that are equal to the specified element (using equals). It runs in O(n) because it iterates the entire collection.
6. How does Collections.binarySearch behave when the key is not found?
When the key is not found, binarySearch returns a negative value: -(insertion point) - 1, where insertion point is the index at which the element would be inserted to keep the list sorted. This allows callers to recover the insertion position: int ip = -(result) - 1.
7. What is the purpose of Collections.nCopies?
Collections.nCopies(n, element) returns an immutable List of size n where every element is the same object reference. It is used for padding, default value initialisation, and test fixtures. Remember that it is one reference repeated — not n independent objects.
Summary
Collections(plural) is a static utility class;Collection(singular) is the root interface.- Key algorithms:
sort,binarySearch,reverse,shuffle,frequency,min,max. - Unmodifiable wrappers prevent writes but remain backed by the original — use
List.copyOffor independent snapshots. - Synchronized wrappers require external synchronization during iteration.
- Prefer
List.of/Set.of/Map.of(Java 9+) for immutable creation andConcurrentHashMapover synchronized wrappers.
Continue Learning
Previous: Comparator | Next: Performance Comparison
Was this guide helpful?
CodeWithVenu is free to read, with no paywall. If this guide saved you time or helped you prepare, a small voluntary contribution helps me write more practical tutorials, architecture guides, and interview-prep content.