Java 9: Immutable collections with List.of / Map.of

Factory methods create compact, unmodifiable collections in one call.

Code
List<String> list = List.of("a", "b", "c");
Map<String, Integer> map = Map.of("x", 1, "y", 2);
System.out.println(list);
System.out.println(map.get("y"));
try { list.add("d"); } catch (UnsupportedOperationException e) {
    System.out.println("immutable: cannot add");
}
Output
[a, b, c]
2
immutable: cannot add
Advertisement

Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.

Published 2026-07-26