Factory methods create compact, unmodifiable collections in one call.
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");
}
[a, b, c]
2
immutable: cannot add
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