Lesson 35 / 38

Sets, Iterating & the Collections Class

Round out the Set family, learn the safe ways to iterate (and remove during iteration), and use java.util.Collections helpers for sorting, immutability and synchronization.

HashSet, LinkedHashSet, TreeSet

The Set family mirrors the Map family exactly, because each is internally backed by a corresponding map: HashSetHashMap, LinkedHashSetLinkedHashMap, TreeSetTreeMap. Same ordering trade-offs apply.

Removing while iterating

Modifying a collection with list.remove(...) while a for-each loop walks it throws ConcurrentModificationException. Use the Iterator's own remove(), or removeIf, instead.

List<Integer> nums = new ArrayList<>(List.of(1, 2, 3, 4, 5));

// Safe:
nums.removeIf(n -> n % 2 == 0);

// Also safe:
Iterator<Integer> it = nums.iterator();
while (it.hasNext()) {
    if (it.next() > 3) it.remove();
}

java.util.Collections helpers

The Collections utility class (not to be confused with the Collection interface) offers static helpers: sort a list in place, wrap one as unmodifiable, or make it thread-safe.

List<Integer> nums = new ArrayList<>(List.of(3, 1, 2));
Collections.sort(nums);
Collections.reverse(nums);

List<Integer> readOnly = Collections.unmodifiableList(nums);
List<Integer> safe = Collections.synchronizedList(nums);