Java · Easy · Free
List.of, Set.of, Map.of (Java 9) — immutability and null rules?
JavaJava 8+Fresher
Collection factories (Java 9)
List.of, Set.of, and Map.of create immutable collections with compact implementations. They reject null keys and values—fail fast at creation.
Map.of(k1,v1,k2,v2)limited to 10 entries; useMap.ofEntriesfor more.- Iteration order fixed for maps (insertion order of pairs).
- Mutating methods throw
UnsupportedOperationException. - Prefer over
Arrays.asListwhen you need true immutability.
java
List<String> tags = List.of("java", "k8s");
Map<String, Integer> scores = Map.of("alice", 10, "bob", 8);
// scores.put("c", 1); // UnsupportedOperationExceptionContrast
List.of vs Collections.unmodifiableList—factory methods are deeply immutable.