Skip to main content

Working with Collection Utilities

1. Sorting Collections

Example: Sort with comparator

List<User> users = ...;
users.sort(Comparator.comparing(User::lastName)
    .thenComparing(User::firstName));
Collections.sort(users, Comparator.comparingInt(User::age).reversed());
MethodUse
Collections.sort(list)Natural order
list.sort(cmp)Direct (Java 8+)
StabilityEqual elements keep order

2. Searching Collections

MethodNotes
Collections.binarySearch(list, key)Sorted only
list.indexOf(o)Linear scan
Streamlist.stream().filter(p).findFirst()

3. Reversing Collections

MethodBehavior
Collections.reverse(list)In-place
list.reversed() JAVA 21+Reverse view

4. Shuffling Collections

MethodDetail
Collections.shuffle(list)Default RNG
Collections.shuffle(list, rng)Reproducible with seeded RNG

5. Creating Unmodifiable Collections

MethodResult
List.of(...)Immutable list (Java 9+)
Set.of(...)Immutable set
Map.of(...) / Map.entry(k,v)Immutable map
List.copyOf(c)Defensive copy (immutable)
Collections.unmodifiableList(l)View (backing still mutable)

6. Creating Synchronized Collections

MethodDetail
Collections.synchronizedList(list)Wraps with synchronized methods
IterationManual sync needed: synchronized(coll){ for(...) }
Modern alternativejava.util.concurrent collections

7. Finding Min and Max

MethodNotes
Collections.min(c) / max(c)Natural order
Collections.min(c, cmp)Custom comparator
Streamstream.min(cmp) returns Optional

8. Replacing Elements

MethodUse
Collections.replaceAll(list, old, new)Replace all occurrences
list.replaceAll(unaryOp)Transform each (Java 8+)
Collections.fill(list, val)Fill all positions

9. Copying Collections

MethodDetail
Collections.copy(dst, src)dst must be ≥ src size
new ArrayList<>(src)Constructor copy
list.stream().toList()Immutable copy

10. Creating Singleton Collections

MethodResult
Collections.singletonList(e)Immutable 1-element list
Collections.singleton(e)Immutable 1-element set
Collections.singletonMap(k,v)Immutable 1-entry map
ModernList.of(e), Set.of(e), Map.of(k,v)

11. Using Frequency Method

MethodReturns
Collections.frequency(c, o)Count of equal elements

12. Using Disjoint Method

MethodReturns
Collections.disjoint(c1, c2)true if no element in common

Was this article helpful?