Collectors.toUnmodifiableMap builds the map and seals it in one step, which is the safest thing to return from a public method.
var raw = List.of("a:1", "b:2", "c:3");
Map<String, Integer> conf = raw.stream()
.map(s -> s.split(":"))
.collect(Collectors.toUnmodifiableMap(p -> p[0], p -> Integer.parseInt(p[1])));
System.out.println(new TreeMap<>(conf));
try {
conf.put("d", 4);
} catch (UnsupportedOperationException e) {
System.out.println("result is unmodifiable");
}
{a=1, b=2, c=3}
result is unmodifiable
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-30