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());
| Method | Use |
|---|---|
Collections.sort(list) | Natural order |
list.sort(cmp) | Direct (Java 8+) |
| Stability | Equal elements keep order |
2. Searching Collections
| Method | Notes |
|---|---|
Collections.binarySearch(list, key) | Sorted only |
list.indexOf(o) | Linear scan |
| Stream | list.stream().filter(p).findFirst() |
3. Reversing Collections
| Method | Behavior |
|---|---|
Collections.reverse(list) | In-place |
list.reversed() JAVA 21+ | Reverse view |
4. Shuffling Collections
| Method | Detail |
|---|---|
Collections.shuffle(list) | Default RNG |
Collections.shuffle(list, rng) | Reproducible with seeded RNG |
5. Creating Unmodifiable Collections
| Method | Result |
|---|---|
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
| Method | Detail |
|---|---|
Collections.synchronizedList(list) | Wraps with synchronized methods |
| Iteration | Manual sync needed: synchronized(coll){ for(...) } |
| Modern alternative | java.util.concurrent collections |
7. Finding Min and Max
| Method | Notes |
|---|---|
Collections.min(c) / max(c) | Natural order |
Collections.min(c, cmp) | Custom comparator |
| Stream | stream.min(cmp) returns Optional |
8. Replacing Elements
| Method | Use |
|---|---|
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
| Method | Detail |
|---|---|
Collections.copy(dst, src) | dst must be ≥ src size |
new ArrayList<>(src) | Constructor copy |
list.stream().toList() | Immutable copy |
10. Creating Singleton Collections
| Method | Result |
|---|---|
Collections.singletonList(e) | Immutable 1-element list |
Collections.singleton(e) | Immutable 1-element set |
Collections.singletonMap(k,v) | Immutable 1-entry map |
| Modern | List.of(e), Set.of(e), Map.of(k,v) |
11. Using Frequency Method
| Method | Returns |
|---|---|
Collections.frequency(c, o) | Count of equal elements |
12. Using Disjoint Method
| Method | Returns |
|---|---|
Collections.disjoint(c1, c2) | true if no element in common |