java.util.Collections Utility
Master java.util.Collections: sorting, searching, reversing, synchronized wrappers, singleton collections, and algorithm utilities.
Master java.util.Collections: sorting, searching, reversing, synchronized wrappers, singleton collections, and algorithm utilities. The guide uses practical examples to explain when to use, when not to use and shows how to apply the ideas in a Spring Boot project. It closes with common pitfalls and production checks so you can apply the pattern with fewer surprises.
Introduction
Before the Stream API, you had to choose between modifying a list in-place or building new collections by hand. java.util.Collections — a final utility class introduced in Java 1.2 — solved the common cases: sorting, binary search, reversal, shuffling, synchronization wrappers, and immutable collection factories.
Compare the two approaches:
List<Integer> numbers = new ArrayList<>(List.of(5, 2, 8, 1, 9));
// In-place mutation with Collections — original list is modified
Collections.sort(numbers);
System.out.println(numbers); // [1, 2, 5, 8, 9] — original list changed
// New list with Stream API — original list is untouched
List<Integer> sorted = numbers.stream().sorted().toList();
System.out.println(sorted); // [1, 2, 5, 8, 9]
System.out.println(numbers); // [5, 2, 8, 1, 9] — still original
Both produce the same sorted result, but the trade-offs are real. Collections.sort() modifies in-place — no allocation, but the original is gone. The Stream API leaves the original untouched — safer for chaining, but allocates intermediate objects. Everything in this post flows from that distinction.
When to Use
| Operation | Method |
|---|---|
| Sort a list in-place | Collections.sort(list) |
| Reverse a list | Collections.reverse(list) |
| Binary search (pre-sorted list) | Collections.binarySearch(list, key) |
| Shuffle (randomize) a list | Collections.shuffle(list) |
| Make a collection thread-safe | Collections.synchronizedCollection(list) |
| Create immutable singleton | Collections.singleton(item) |
| Create immutable empty list/set/map | Collections.emptyList(), emptySet(), emptyMap() |
| Fill a list with a value | Collections.fill(list, value) |
| Rotate list elements | Collections.rotate(list, distance) |
| Frequency of an element | Collections.frequency(list, item) |
| Min and max | Collections.min(collection), Collections.max(collection) |
When NOT to Use
- Functional transformations: If you want a new sorted list without modifying the original, use the Stream API:
list.stream().sorted().toList(). The Stream approach is cleaner when you need immutability. - Thread-safe collections:
synchronizedCollection()wraps a collection but does not make iteration safe. For concurrent read-write access, useCopyOnWriteArrayListor explicit locking around iteration. - Shared mutable state: Calling
fill()orrotate()on a shared list overwrites data. Document when you do this intentionally, and avoid it when others expect the list to be preserved.
Collections Utility Architecture
Sorting and Searching
Collections.sort(list) sorts in-place using TimSort, a hybrid of merge sort and insertion sort. It runs in O(n log n) time and allocates O(n) auxiliary space. The sort is stable, so equal elements keep their relative order from the input. If you need a different order, sort(list, comparator) takes a comparator, so elements do not have to implement Comparable.
binarySearch() finds elements in O(log n) time, but only works on sorted lists. Call it on an unsorted list and the result is meaningless. When a key is not found, the method returns a negative value encoding the insertion point as -(insertionPoint) - 1. Callers decode this to find where to insert the missing key.
You sort once, then search repeatedly. The sort is the expensive part, so you pay that cost once and then run binary searches on the same sorted list. Re-sorting before every search wastes the effort you saved.
flowchart TD
A1["sort(List)"]
A2["sort(List, Comparator)"]
A3["binarySearch(List, Key)"]
A4["binarySearch(List, Key, Comparator)"]
A1 --> A2
A2 --> A3
A3 --> A4
Mutators
These methods modify lists in-place and return nothing. They predate the Stream API and still make sense when you want to change a list without allocating new objects. reverse() flips element order, shuffle() randomizes it, fill() overwrites every element with a single value, rotate() shifts elements by a distance, and swap() exchanges two positions. All run in O(n) time with no extra allocation.
The Stream API takes the opposite approach: list.stream().sorted().toList() produces a new sorted list and leaves the original untouched. In-place sort is faster and uses less memory when you do not need the original. The Stream approach is safer when you do. Pick based on what you actually need.
flowchart TD
B1["reverse(List)"]
B2["shuffle(List)"]
B3["fill(List, Element)"]
B4["rotate(List, distance)"]
B5["swap(List, i, j)"]
Wrappers
Wrappers are views backed by the original collection. If you modify the backing collection, the wrapper shows those changes. The three main variants are synchronizedCollection(), unmodifiableCollection(), and checkedCollection(), each adding a different layer of behavior.
synchronizedCollection() synchronizes individual mutations but not iteration. Iterate without an explicit synchronized(list) block and ConcurrentModificationException fires. For read-mostly concurrent access, CopyOnWriteArrayList is usually the better fit.
unmodifiableCollection() blocks structural changes but does not make the underlying collection immutable. Someone with a reference to the backing list can still modify it, and those changes show through the wrapper. For actual immutability, List.of() and its Java 9 siblings have no backing store to corrupt.
checkedCollection() enforces the type argument at insertion time. Adding a wrong type throws ClassCastException right then, not later at retrieval. This means you catch type errors at the point where they are easiest to fix.
flowchart TD
C1["synchronizedCollection(List)"]
C2["synchronizedMap(Map)"]
C3["unmodifiableCollection(List)"]
C4["checkedCollection(List, Type)"]
Factories
Factory methods create lightweight immutable collections for specific situations. singleton(), singletonList(), and singletonMap() wrap a single element in an immutable collection. Use these when an API expects a collection but you only have one value, or when you want a one-off set or map without the overhead of building a full collection.
emptyList(), emptySet(), and emptyMap() return shared singleton instances. Returning null forces every caller to null-check. Returning an empty collection lets callers iterate without special handling. The JVM shares these singletons internally, so there is no allocation cost.
nCopies(n, obj) creates a list holding n references to the same object. This is one object repeated n times, not n copies of the object. Mutate that object through one list entry and all n entries change. Only use nCopies() with values you guarantee will never change.
Java 9 gave us List.of(), Set.of(), and Map.of() as cleaner alternatives to the Collections.unmodifiable* factory methods. The newer methods create truly immutable collections with no backing list, making them the safer choice in security-sensitive contexts.
flowchart TD
D1["singleton()"]
D2["emptyList/Set/Map()"]
D3["nCopies(n, obj)"]
D4["listOf() / setOf() / mapOf()"]
Code Examples
Sorting, Binary Search, and Related Operations
import java.util.*;
// Sort in-place (natural order, must be Comparable)
List<Integer> numbers = new ArrayList<>(List.of(5, 2, 8, 1, 9));
Collections.sort(numbers);
System.out.println(numbers); // [1, 2, 5, 8, 9]
// Sort with comparator
List<String> names = new ArrayList<>(List.of("Charlie", "Alice", "Bob"));
Collections.sort(names, Comparator.comparingInt(String::length));
System.out.println(names); // [Bob, Alice, Charlie]
// Binary search — list MUST be sorted first
List<Integer> sorted = new ArrayList<>(List.of(1, 3, 5, 7, 9));
int idx = Collections.binarySearch(sorted, 5); // 2 (index)
int neg = Collections.binarySearch(sorted, 4); // -3 (insertion point: ~(-3)-1 = -2)
int notFound = Collections.binarySearch(sorted, 10); // -6 (past end)
// Binary search with comparator
int idxComp = Collections.binarySearch(sorted, 5, Comparator.naturalOrder());
Mutators — Reverse, Shuffle, Rotate, Fill
import java.util.*;
List<Integer> list = new ArrayList<>(List.of(1, 2, 3, 4, 5));
// Reverse
Collections.reverse(list);
System.out.println(list); // [5, 4, 3, 2, 1]
// Shuffle (pseudo-random)
Collections.shuffle(list);
Collections.shuffle(list, new Random(42)); // reproducible shuffle
// Rotate — element at index i moves to (i + distance) % size
List<String> queue = new ArrayList<>(List.of("A", "B", "C", "D", "E"));
Collections.rotate(queue, 2);
System.out.println(queue); // [D, E, A, B, C] (A and B moved to end)
Collections.rotate(queue, -1); // rotate back: [E, A, B, C, D]
// Fill — replaces ALL elements with a single value
List<String> placeholders = new ArrayList<>(List.of("X", "Y", "Z"));
Collections.fill(placeholders, "TBD");
System.out.println(placeholders); // [TBD, TBD, TBD]
Thread-Safe Wrappers
import java.util.*;
List<Integer> syncList = Collections.synchronizedList(new ArrayList<>());
Map<String, Integer> syncMap = Collections.synchronizedMap(new HashMap<>());
Set<Double> syncSet = Collections.synchronizedSet(new HashSet<>());
// Iteration requires synchronization — the wrapper does not make iteration thread-safe
synchronized (syncList) {
for (Integer item : syncList) {
// safe concurrent iteration
}
}
// Unmodifiable wrapper — prevents modification
List<String> readOnly = Collections.unmodifiableList(List.of("a", "b"));
// readOnly.add("c"); // throws UnsupportedOperationException
// Checked collection — runtime type safety
List<String> checked = Collections.checkedList(new ArrayList<>(), String.class);
checked.add("hello");
// checked.add(42); // throws ClassCastException at add() time
Singleton and Empty Factories
import java.util.*;
Map<String, Integer> singletonMap = Collections.singletonMap("key", 42);
List<String> singletonList = Collections.singletonList("only");
Set<Double> singletonSet = Collections.singleton(3.14);
// Empty collections — immutable, purpose-specific
List<Object> emptyList = Collections.emptyList();
Set<Integer> emptySet = Collections.emptySet();
Map<String, Object> emptyMap = Collections.emptyMap();
// nCopies — creates an immutable list of n references to the same object
List<String> repeated = Collections.nCopies(3, "DEFAULT");
System.out.println(repeated); // [DEFAULT, DEFAULT, DEFAULT]
// Note: nCopies returns the SAME object reference repeated n times — mutation affects all entries
Algorithms — min, max, frequency, disjoint
import java.util.*;
List<Integer> nums = List.of(1, 5, 3, 7, 5, 9, 5);
// Min and max
int min = Collections.min(nums);
int max = Collections.max(nums);
String shortest = Collections.min(List.of("a", "ab", "abc"), Comparator.comparingInt(String::length));
// Frequency
int count = Collections.frequency(nums, 5); // 3
// Disjoint — true if no common elements
boolean overlap = Collections.disjoint(List.of(1, 2, 3), List.of(4, 5, 6)); // true
boolean noOverlap = Collections.disjoint(List.of(1, 2, 3), List.of(3, 4, 5)); // false
// Add all (efficient bulk add)
List<String> target = new ArrayList<>(List.of("a", "b"));
Collections.addAll(target, "c", "d", "e"); // [a, b, c, d, e]
// Replace all
List<String> names = new ArrayList<>(List.of("Alice", "Bob", "Alice"));
Collections.replaceAll(names, "Alice", "ALICE");
System.out.println(names); // [ALICE, Bob, ALICE]
Failure Scenarios
| Scenario | Problem | Solution |
|---|---|---|
binarySearch on unsorted list |
Incorrect index or insertion point | Always sort before binary search; binarySearch does not sort |
synchronizedList iteration without synchronization |
ConcurrentModificationException |
Wrap iteration in synchronized(list) block |
Collections.fill destroys all existing elements |
Accidental overwriting of data | Only use fill when you intentionally want all elements replaced |
nCopies with mutable object |
All entries reference the same object instance | Never mutate elements from an nCopies list; use Collections.nCopies only for immutable values |
Collections.min on empty collection |
NoSuchElementException |
Check isEmpty() before calling min/max |
Trade-off Table
| Aspect | Collections utility |
Stream API equivalent |
|---|---|---|
| In-place mutation | Yes | No (produces new collection) |
| Binary search | Yes, in-place | list.stream().sorted().toList() then binary search |
| Thread-safety wrapper | Yes | CopyOnWriteArrayList, Collections.synchronizedList() |
| API complexity | Simple static methods | Fluent, declarative |
| Performance | Direct in-place, no allocation | Allocates intermediate objects |
Observability Checklist
import java.util.Collections;
import java.util.stream.Collectors;
import java.time.Instant;
// Monitored sorting
public void monitoredSort(List<Integer> data, String operationId) {
long start = System.nanoTime();
Collections.sort(data);
long duration = System.nanoTime() - start;
System.out.println("metric=sorting duration_ns=" + duration +
" size=" + data.size() + " operation=" + operationId +
" timestamp=" + Instant.now());
}
// Wrap to track empty collection access
public <T> List<T> safeEmptyList() {
System.out.println("metric=empty_collection_requested type=list");
return Collections.emptyList();
}
- Track sorting operation frequency and duration per list size.
- Monitor
synchronizedListcontention metrics in multi-threaded contexts. - Instrument
frequency()calls to identify duplicate detection patterns. - Log
emptyList()/emptySet()/emptyMap()calls as potential null-handling indicators. - Use structured metric tags for collection operations with size and operation type.
Security Notes
- Mutation through
nCopies:Collections.nCopies(n, mutableObject)shares the same object reference across all n positions. Any mutation through one reference is visible through all positions — this is a common source of accidental data corruption. synchronizedListdoes not make iterations thread-safe: Even with the wrapper, concurrent iteration and modification throwsConcurrentModificationException. You must synchronize manually during iteration.- Checked collection security:
Collections.checkedCollection()provides runtime type enforcement against the specific type used at creation — but it cannot prevent type-unsafe serialization or reflection-based injection of wrong types. - Immutable wrappers and serialization:
Collections.unmodifiableList()creates a wrapper — if the underlying list is modified via a reference obtained before wrapping, the unmodifiable wrapper can reflect those changes. Always create the unmodifiable view last.
Pitfalls
binarySearchrequires a sorted list: If the list is not sorted,binarySearchreturns an undefined result. It will NOT sort the list for you. Sort first, then search.synchronizedList/synchronizedMapare poorly named: These wrappers synchronize mutations but NOT iterations. Concurrent reads during writes require explicit synchronization — the wrapper alone is insufficient for concurrent access patterns.Collections.sort()uses TimSort: It is stable but requires O(n log n) time and O(n) auxiliary space. For nearly sorted data it approaches O(n). Sorting an already-sorted list in a parallel stream does not make it parallel — uselist.parallelStream()withsorted()for parallel sort.nCopiesreturns the same object reference:Collections.nCopies(3, new Object())does not create 3 distinct objects — it creates 1 object shared 3 times. This is efficient but dangerous if you later iterate and mutate.Collections.rotate(list, distance)when distance equals 0: This is a no-op — no error, but verify your distance calculation does not produce 0 unexpectedly when you expected a rotation.
Quick Recap
Collections.sort(list)sorts in-place (ascending by natural order); usesort(list, comparator)for custom order.Collections.binarySearch(list, key)requires the list to be sorted first — returns index or negative insertion point.Collections.reverse(),rotate(),shuffle(),fill()are all in-place mutators.Collections.synchronizedList()/synchronizedMap()wrap but do NOT make iteration thread-safe.Collections.emptyList()/emptySet()/emptyMap()return immutable, singleton empty collections.Collections.singleton(),singletonList(),singletonMap()create immutable single-element collections.nCopies(n, obj)creates n references to the same object — never mutate the returned list.- Use Stream API for read-only transformations that should remain immutable.
Interview Questions
Collections.sort() and list.stream().sorted().toList()?List<Integer> numbers = new ArrayList<>(List.of(5, 2, 8, 1, 9));
// In-place mutation — original list is modified
Collections.sort(numbers);
System.out.println(numbers); // [1, 2, 5, 8, 9] — changed permanently
// New list — original untouched
List<Integer> sorted = numbers.stream().sorted().toList();
System.out.println(sorted); // [1, 2, 5, 8, 9]
System.out.println(numbers); // [5, 2, 8, 1, 9] — still original
Collections.sort() uses TimSort in O(n log n) time with O(n) auxiliary space and is stable. The Stream API version allocates intermediate objects but leaves the original untouched. Use sort() when you want mutation; use Stream API when you need immutability or chaining.
Collections.synchronizedList() actually synchronize?List<Integer> syncList = Collections.synchronizedList(new ArrayList<>());
syncList.add(1);
syncList.add(2);
syncList.add(3);
// WRONG — throws ConcurrentModificationException
for (Integer item : syncList) {
// safe concurrent iteration
}
// CORRECT — wrap the iteration block
synchronized (syncList) {
for (Integer item : syncList) {
// safe
}
}
Each add(), remove(), set(), and clear() is synchronized individually, but the wrapper cannot know when you will iterate. You must hold the monitor yourself during iteration. For read-mostly concurrent access, CopyOnWriteArrayList is usually the better fit — it optimises for frequent reads over frequent writes.
binarySearch when the key is not found?List<Integer> sorted = new ArrayList<>(List.of(1, 3, 5, 7, 9));
int idx = Collections.binarySearch(sorted, 5); // 2 (found at index 2)
int neg = Collections.binarySearch(sorted, 4); // -3 (not found)
// Recovery: insertion point = -(result) - 1 = -(-3) - 1 = 2
int notFound = Collections.binarySearch(sorted, 10); // -6 (past end)
// insertion point = -(result) - 1 = -(-6) - 1 = 5 (append at end)
The formula is -(insertionPoint) - 1. So a return value of -3 means insertion point 2. A return of -6 means insertion point 5 — past the last element. Always sort before searching; binarySearch does not sort for you.
Collections.nCopies dangerous with mutable objects?// WRONG — nCopies with a mutable object
List<StringBuilder> bad = new ArrayList<>(Collections.nCopies(3, new StringBuilder("X")));
bad.get(0).append(" updated");
System.out.println(bad); // [X updated, X updated, X updated] — all three changed!
// CORRECT — nCopies with immutable objects only
List<String> safe = Collections.nCopies(3, "DEFAULT");
System.out.println(safe); // [DEFAULT, DEFAULT, DEFAULT]
// safe.get(0).append("!"); // String has no append — won't compile
One object. n references. Mutate through one index and every entry reflects it. Use nCopies only with objects you can guarantee will never change — primitives, strings, or immutable value types.
Collections.unmodifiableList() and List.of()?// unmodifiableList — wrapper, not a copy
List<String> original = new ArrayList<>(List.of("a", "b"));
List<String> view = Collections.unmodifiableList(original);
original.add("c"); // modifies backing list
System.out.println(view); // [a, b, c] — view reflects the change!
// List.of() — true immutability, no backing store
List<String> trulyImmutable = List.of("a", "b");
trulyImmutable.add("c"); // throws UnsupportedOperationException
// No backing list exists to corrupt it
Collections.unmodifiableList() wraps the original — it does not copy it. Anyone with a reference to the underlying list can still modify it. List.of() (Java 9+) creates a standalone immutable list with no backing store. For security-sensitive contexts, prefer List.of().
Collections.disjoint() and when should you use it?Collections.rotate() do and how does the distance parameter work?(i + distance) % size.
List<String> queue = new ArrayList<>(List.of("A", "B", "C", "D", "E"));
Collections.rotate(queue, 2);
System.out.println(queue); // [D, E, A, B, C]
// Positive = shift forward (head moves to tail)
// Negative = shift backward (tail moves to head)
Collections.rotate(queue, -1);
System.out.println(queue); // [E, A, B, C, D]
// Common use: rotating a circular buffer or deck of cards
// distance = 0 is a no-op — no exception, nothing happens
Collections.rotate(queue, 0); // queue unchanged
A distance of 0 silently does nothing — no exception thrown. Verify your distance calculation does not produce 0 when you expected a rotation.
Collections.replaceAll differ from iterating with set()?Collections.shuffle() with a Random seed?Collections.frequency() return for an empty collection or absent element?Collections.emptyIterator() and returning a new empty iterator?Collections.nCopies() versus creating an actual list of identical elements?Collections.addAll() do and why is it more efficient than multiple add() calls?Collections.max() and Collections.min() with and without a comparator?Collections.binarySearch() behave when the list is not sorted?List<Integer> unsorted = new ArrayList<>(List.of(9, 3, 1, 5, 2));
// WRONG — unsorted list, result is garbage
int wrong = Collections.binarySearch(unsorted, 3); // unpredictable!
// CORRECT — sort first, then search
Collections.sort(unsorted); // [1, 2, 3, 5, 9]
int correct = Collections.binarySearch(unsorted, 3); // 2 ✓
binarySearch() does not sort, validate, or warn. It trusts the caller completely. The only symptom of an unsorted list is a wrong result with no error thrown. The standard pattern is one sort() followed by many binarySearch() calls on the same sorted list — pay the sort cost once, search cheaply many times.
Collections.min() on a collection containing null elements?Collections.fill() and when should you use it?Collections.checkedCollection() and a cast in the caller?Collections.indexOfSubList() work and what does the return value mean?Collections.reverse() is called on an empty list or single-element list?Further Reading
- Oracle: Collections Framework Tutorial — official guide to the Java Collections Framework
- Baeldung: Java Collections — comprehensive coverage of
Collectionsutility methods - TimSort: The algorithm behind Collections.sort() — understand the O(n log n) sorting algorithm powering Java’s in-place sort
- CopyOnWriteArrayList vs Collections.synchronizedList — when to choose each thread-safe list implementation
- Java 9 immutable collection factories — evolution of immutable collection creation from
Collections.unmodifiableList()toList.of() - ArrayList — most common collection used with Collections utility methods
- HashMap — map utility methods in Collections
- Iterating Collections — iteration patterns with utility method context
- Java Generic Classes — type parameters and wildcards underlying Collections sorting comparators
- Java Stream API — comparator expressions used with
sort()andbinarySearch()
Conclusion
java.util.Collections predates the Stream API, but it is far from obsolete. I still reach for it whenever I need actual in-place mutation — the Stream API produces new collections, not modified ones.
The sort() and binarySearch() pair trips up developers most. Remember: binarySearch() does not sort for you. Sort first, then search. Collections.sort() uses TimSort and is stable — equal elements keep their relative order — but needs O(n) auxiliary space.
The synchronization wrappers have a trap: they synchronize mutations but not iteration. Concurrent modification during iteration throws ConcurrentModificationException regardless of the wrapper. If you need concurrent iteration, wrap it in a synchronized(list) block, or reach for CopyOnWriteArrayList or the concurrent collections instead.
Factory methods like singleton(), emptyList(), and nCopies() are useful for guard clauses and default values. Watch out for nCopies() — all n entries point to the same object. Mutate one, and every entry changes.
Streams and Collections fit together naturally. Streams eat collections, and Comparator expressions used with sort() tap into the same java.util.function interfaces Streams do.
Category
Related Posts
Abstract Classes in Java
Learn about partially implemented classes that define contracts for subclasses using abstract methods and concrete implementations.
Arithmetic Operators in Java
Master Java arithmetic operators: addition, subtraction, multiplication, division, and modulo with integer division gotchas and operator precedence explained.
Array Basics in Java
Learn Java array fundamentals: declaration, initialization, element access, and the length property explained simply.