Java Collections Utility: Sorting, Searching, and Wrappers
Learn how java.util.Collections sorts and searches lists, how access affects operation costs, and how synchronized wrappers and unmodifiable views behave.
Reference for java.util.Collections sorting, searching, list mutation, synchronized wrappers, and collection factories. Examples explain binary-search results, access-dependent costs, and the difference between a live unmodifiable view and a snapshot.
Java Collections Utility: Sorting, Searching, and Wrappers
Introduction
java.util.Collections provides static methods and wrapper factories for existing collections. Some methods mutate their input; a stream operation such as list.stream().sorted().toList() returns a separate, unmodifiable result.
Compare the two approaches:
List<Integer> numbers = new ArrayList<>(List.of(5, 2, 8, 1, 9));
// Sort this list in place
Collections.sort(numbers);
System.out.println(numbers); // [1, 2, 5, 8, 9]
// Sort a separate copy with a stream
List<Integer> original = new ArrayList<>(List.of(5, 2, 8, 1, 9));
List<Integer> sorted = original.stream().sorted().toList();
System.out.println(sorted); // [1, 2, 5, 8, 9]
System.out.println(original); // [5, 2, 8, 1, 9]
Both produce sorted values. Collections.sort() changes the list it receives, while the stream version leaves its source unchanged and returns an unmodifiable result. Choose based on whether the caller should keep the original order.
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) |
| Synchronize individual collection operations | Collections.synchronizedCollection(list) |
| Create unmodifiable singleton | Collections.singleton(item) |
| Use an unmodifiable 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(). Its result is unmodifiable; the source list stays unchanged. - Concurrent access:
synchronizedCollection()synchronizes individual methods, but traversal needs a lock around the whole operation. UseCopyOnWriteArrayListwhen writes are rare and snapshot iteration fits, or synchronize on the wrapper during traversal. - 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) delegates to List.sort and requires a modifiable list. The API guarantees a stable sort; the exact algorithm and resource use can depend on the list implementation. Use sort(list, comparator) to supply an ordering instead of relying on natural ordering.
Collections.binarySearch() requires a list sorted according to the same ordering used for the search. On a RandomAccess list with near-constant-time positional access, it runs in O(log n) time. On a large list without RandomAccess, Java SE 27 documents O(n) link traversals and O(log n) element comparisons. If the key is absent, the result is -(insertionPoint) - 1.
If the same list will be searched repeatedly, sort it once and use the same ordering for each search. Sorting before every lookup adds unnecessary work.
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 a list in place. reverse() changes the order, shuffle() permutes elements, fill() replaces each element, rotate() shifts positions, and swap() exchanges two positions. Their costs differ; the list’s access model matters too.
| Method | Cost notes |
|---|---|
fill() |
The Java SE 27 Collections API specifies linear time because each list position is replaced. |
shuffle() |
The API specifies linear time; for a large list without RandomAccess, its implementation uses an array to avoid quadratic behavior. |
swap() |
No universal constant-time bound is specified. Near-constant indexed access makes it constant work; sequential access can require traversal to the positions. |
reverse() |
The Java SE 27 API specifies linear time. |
rotate() |
The API chooses different strategies based on the list’s access model; cost depends on that strategy and implementation. |
The Java SE 27 Collections API specifies costs for some algorithms, but not a single bound for every list operation. The RandomAccess API explains why generic algorithms may need different strategies for array-backed and sequential lists.
list.stream().sorted().toList() returns a separate sorted list and leaves its source unchanged. The two approaches differ in ownership and mutability; avoid choosing between them based on an assumed speed or allocation advantage.
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 change the backing collection, the wrapper reflects that change. Use synchronizedCollection(), unmodifiableCollection(), or checkedCollection() to add the behavior you need.
Synchronized wrappers lock individual operations, but iteration through an iterator, spliterator, or stream needs a separate synchronized block on the returned wrapper. Without it, concurrent traversal can behave unpredictably; a fail-fast iterator may throw ConcurrentModificationException, but that is not a safety guarantee. CopyOnWriteArrayList may fit workloads with many reads and few writes, if snapshot iteration suits the use case.
unmodifiableCollection() and unmodifiableList() prevent changes through the returned reference, but they are live views: changes made through the backing collection remain visible. List.copyOf(source) instead returns an unmodifiable snapshot of the collection structure. It is shallow, so mutable elements are still shared.
List<String> backing = new ArrayList<>(List.of("a", "b"));
List<String> view = Collections.unmodifiableList(backing);
List<String> snapshot = List.copyOf(backing);
backing.add("c");
System.out.println(view); // [a, b, c]
System.out.println(snapshot); // [a, b]
checkedCollection() checks the type at insertion time. Adding a value of the wrong type throws ClassCastException then, rather than later when the value is read.
flowchart TD
C1["synchronizedCollection(List)"]
C2["synchronizedMap(Map)"]
C3["unmodifiableCollection(List)"]
C4["checkedCollection(List, Type)"]
Factories
Factory methods provide unmodifiable collection structures for specific situations. singleton(), singletonList(), and singletonMap() return one-element collections. Use them when an API expects a collection but you have only one value.
emptyList(), emptySet(), and emptyMap() return unmodifiable empty collections. Returning an empty collection lets callers iterate without a null check.
nCopies(n, obj) returns an unmodifiable list containing n references to the same object. Mutating a mutable element through one position is visible through every position. Use independent instances if that is not intended.
List.of(), Set.of(), and Map.of() provide unmodifiable collection structures from their arguments. An unmodifiable structure does not make mutable elements immutable.
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.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class CollectionsBasicsDemo {
public static void main(String[] args) {
List<Integer> numbers = new ArrayList<>(List.of(5, 2, 8, 1, 9));
Collections.sort(numbers);
System.out.println(numbers);
List<String> names = new ArrayList<>(List.of("Charlie", "Alice", "Bob"));
Collections.sort(names, Comparator.comparingInt(String::length));
System.out.println(names);
List<Integer> sorted = new ArrayList<>(List.of(1, 3, 5, 7, 9));
int index = Collections.binarySearch(sorted, 5);
int insertionPoint = -Collections.binarySearch(sorted, 4) - 1;
System.out.println("index of 5 = " + index);
System.out.println("insertion point for 4 = " + insertionPoint);
}
}
Save this as CollectionsBasicsDemo.java, then run javac CollectionsBasicsDemo.java && java CollectionsBasicsDemo:
[1, 2, 5, 8, 9]
[Bob, Alice, Charlie]
index of 5 = 2
insertion point for 4 = 2
This example uses List.of(), available since Java 9.
Mutators: reverse, shuffle, rotate, and 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
// For a non-empty list, element i moves to floorMod((long) 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<>());
// Synchronize on the wrapper while traversing it
synchronized (syncList) {
for (Integer item : syncList) {
// other threads must access the list through syncList
}
}
// 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);
// Unmodifiable empty collections
List<Object> emptyList = Collections.emptyList();
Set<Integer> emptySet = Collections.emptySet();
Map<String, Object> emptyMap = Collections.emptyMap();
// nCopies — creates an unmodifiable list of n references to the same object
List<String> repeated = Collections.nCopies(3, "DEFAULT");
System.out.println(repeated); // [DEFAULT, DEFAULT, DEFAULT]
// Each position refers to the same object; mutable state is shared
Algorithms: min, max, frequency, and 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 supplied elements
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 |
The API leaves the result undefined | Sort using the search ordering first; binarySearch does not sort |
synchronizedList traversal without its monitor |
Traversal is not protected from concurrent changes | Synchronize on the wrapper for the entire traversal; fail-fast detection is best effort |
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 | Use it only when shared state is intended; create separate objects for independent state |
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 | Available; cost depends on list access | No built-in binary search; sort or scan a materialized result |
| Concurrent access | Synchronized wrappers need an external lock during traversal | CopyOnWriteArrayList offers snapshot iteration |
| API style | Static utility methods | Fluent transformations |
| Ownership and storage | Mutates the list; operation and implementation determine temporary storage | Returns an unmodifiable list and leaves the source unchanged |
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 one object reference across all positions. A mutation through one entry is visible through the others. - Iteration through synchronized wrappers needs a lock: Synchronize on the returned wrapper while traversing it. A fail-fast iterator may throw
ConcurrentModificationException, but that is best-effort detection. - 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. - Unmodifiable views are live:
Collections.unmodifiableList()reflects changes made through another reference to its backing list. UseList.copyOf()for an unmodifiable snapshot of the collection structure; it is still shallow.
Pitfalls
binarySearchrequires a sorted list: If the list is not sorted, the API leaves the result undefined. It does not sort the list for you. Sort first, then search.- Iteration needs a shared lock: Synchronize on the returned wrapper for the whole traversal, and make sure other access to the backing collection uses that same wrapper.
- Sort costs are not one fixed promise: The API guarantees stability. The algorithm and temporary storage can depend on the list implementation and input. Parallel streams may add overhead; measure before using one for sorting.
nCopiesreturns the same object reference:Collections.nCopies(3, new Object())does not create 3 distinct objects. It creates one object shared across all positions. Use it when sharing that reference is intended; create separate objects when each position needs independent state.Collections.rotate(list, distance)with a distance of 0: The list stays unchanged. Check the computed distance if 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 a sorted list. It is O(log n) on random-access lists; large sequential lists may require O(n) link traversals.Collections.reverse(),rotate(),shuffle(), andfill()mutate the list in place. The API specifies linear time for reverse, shuffle, and fill; rotate and swap costs depend on the list’s access model and implementation.Collections.synchronizedList()/synchronizedMap()synchronize individual operations; lock the wrapper during traversal.Collections.emptyList()/emptySet()/emptyMap()return unmodifiable empty collections.Collections.singleton(),singletonList(),singletonMap()create unmodifiable single-element collections.nCopies(n, obj)creates n references to the same object; use separate objects when each position needs independent state.- Use
stream().sorted().toList()when the source list should remain unchanged.
Interview questions
Collections.sort() and list.stream().sorted().toList()?Collections.sort() changes the list it receives. The stream version returns a separate unmodifiable result.
List<Integer> numbers = new ArrayList<>(List.of(5, 2, 8, 1, 9));
// In-place mutation
Collections.sort(numbers);
System.out.println(numbers); // [1, 2, 5, 8, 9]
// A stream returns a separate list
List<Integer> original = new ArrayList<>(List.of(5, 2, 8, 1, 9));
List<Integer> sorted = original.stream().sorted().toList();
System.out.println(sorted); // [1, 2, 5, 8, 9]
System.out.println(original); // [5, 2, 8, 1, 9]
The Java SE 27 Collections API delegates sorting to List.sort and guarantees stability. The exact algorithm and resource use can depend on the list implementation. Use sort() when changing the input is intended; use the stream result when you need to keep the original order.
Collections.synchronizedList() actually synchronize?List<Integer> syncList = Collections.synchronizedList(new ArrayList<>());
syncList.add(1);
syncList.add(2);
syncList.add(3);
// Unsafe if another thread can modify the list; it may or may not throw
for (Integer item : syncList) {
// traversal is not protected by the wrapper's operation-level lock
}
// CORRECT — wrap the iteration block
synchronized (syncList) {
for (Integer item : syncList) {
// traversal holds the wrapper's monitor
}
}
Without the external lock, traversal can behave unpredictably. A fail-fast iterator may report a concurrent modification, but that is best-effort bug detection, not a thread-safety guarantee. CopyOnWriteArrayList can fit read-heavy workloads when snapshot iteration is acceptable.
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 and 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
Every entry refers to the same object. Mutating it through one index changes what you see through the others. Use nCopies when sharing a reference is intended; create separate objects when each position needs independent state.
Collections.unmodifiableList() and List.copyOf()?unmodifiableList is a live view of its backing list. List.copyOf creates an unmodifiable snapshot of the collection structure.
// Live unmodifiable view
List<String> original = new ArrayList<>(List.of("a", "b"));
List<String> view = Collections.unmodifiableList(original);
List<String> snapshot = List.copyOf(original);
original.add("c");
System.out.println(view); // [a, b, c]
System.out.println(snapshot); // [a, b]
// Both views reject structural changes through their references
view.add("d"); // throws UnsupportedOperationException
snapshot.add("d"); // throws UnsupportedOperationException
Changes to the backing list remain visible through the live view, but not through the snapshot. List.copyOf is shallow: mutable elements inside the list remain shared. Neither operation makes those elements immutable.
Collections.disjoint() and when should you use it?Collections.rotate() do and how does the distance parameter work?i moves to Math.floorMod((long) i + distance, size), which keeps the index non-negative when the distance is negative and avoids overflow in the addition.
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()?Random with a fixed seed. That makes the permutation repeatable with the same Java implementation and call pattern. Keep the seed and input order in the test so the setup is clear.Collections.frequency() return for an empty collection or absent element?equals().Collections.emptyIterator() and returning a new empty iterator?Collections.emptyIterator() returns an iterator with no elements. Code should depend on that behavior, not on the identity or allocation strategy of the returned iterator.Collections.nCopies() versus creating an actual list of identical elements?nCopies(n, obj) when a fixed-size unmodifiable list of repeated references is intended. If obj is mutable, every position refers to the same instance. Create separate instances when each position needs independent state.Collections.addAll() do?Collections.addAll(collection, elements...) adds the supplied elements and returns whether the collection changed. It can make a call site concise; performance depends on the collection implementation.Collections.max() and Collections.min() with and without a comparator?Collections.binarySearch() receives an unsorted list?List<Integer> unsorted = new ArrayList<>(List.of(9, 3, 1, 5, 2));
// Unsorted input: the result is undefined
int result = Collections.binarySearch(unsorted, 3);
// CORRECT — sort first, then search
Collections.sort(unsorted); // [1, 2, 3, 5, 9]
int correct = Collections.binarySearch(unsorted, 3); // 2 ✓
binarySearch() does not validate the ordering. Sort with the same ordering first. Repeated searches then avoid sorting each time, though lookup cost still depends on the list’s access model.
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?-1 if there is no match. An empty sublist matches at index 0.Collections.reverse() is called on an empty list or single-element list?Collections.reverse leaves an empty or single-element list unchanged. The list has no pair of elements whose order could change.Further reading
- Java SE 27 Collections API — method contracts and documented complexity notes
- Java SE 27 RandomAccess API — the marker interface used by algorithms to choose access strategies
- Java SE 27 List API — list sorting, unmodifiable copies, and other list contracts
- Oracle Collections Framework Tutorial — an introduction to the Java Collections Framework
- 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
Use Collections.sort() when the list should change in place. Before calling binarySearch(), sort with the same ordering; lookup cost depends on whether the list supports fast positional access.
Synchronized wrappers protect individual operations. Hold the wrapper’s monitor across the full traversal, and avoid direct access to the backing collection. A fail-fast exception can reveal a bug, but it does not make concurrent iteration safe.
Choose a live unmodifiable view when changes through the backing collection should remain visible. Use List.copyOf() when callers need an unmodifiable snapshot of the list structure. Remember that this copy is shallow, and nCopies() shares one reference across every position.
Category
Related Posts
Abstract Classes in Java: Interfaces and Composition
Compare Java interfaces, abstract classes, and composition, then see when shared state, default methods, or sealed types change the design choice.
Arithmetic Operators in Java: Division, Overflow, Promotion
Compare Java arithmetic with runnable examples of division, negative remainders, overflow, type promotion, and BigDecimal for decimal money.
Java Array Basics: Length, Bounds, Copies, and Resizing
Learn Java arrays through runtime-sized allocation, bounds checks, aliasing, copying, and the fixed length that distinguishes them from ArrayList.