ProLesson 7.9Intermediate2 min readUpdated 30 October 2026
Immutable and sequenced collections
Create unmodifiable collections with List.of and copyOf, know how they differ from unmodifiable views, and use Java 21 sequenced collections.
Immutable collections can't change after creation. They're safe to share, safe across threads, and they stop whole classes of bugs. Java 21 also added sequenced collections, a single way to get the first and last element of any ordered collection.
01Creating immutable collections (Java 9+)
Immutable.java
import java.util.List;
import java.util.Map;
import java.util.Set;
public class Immutable {
public static void main(String[] args) {
List<String> roles = List.of("ADMIN", "EDITOR");
Set<Integer> codes = Set.of(200, 201, 204);
Map<String, Integer> limits = Map.of("free", 5, "pro", 100);
System.out.println(roles.contains("ADMIN"));
System.out.println(limits.get("pro"));
try {
roles.add("GUEST");
} catch (UnsupportedOperationException e) {
System.out.println("Can't modify: " + e.getClass().getSimpleName());
}
System.out.println(codes.size());
}
}true 100 Can't modify: UnsupportedOperationException 3
Rules for List.of, Set.of and Map.of:
- No
nullelements, keys or values (NullPointerException). Set.ofandMap.ofreject duplicates (IllegalArgumentException).Set.ofandMap.ofhave no defined iteration order.
Loading the rest of the lesson…