โ— Shell
clean mode source โ†—

Immutable map creation

Code Comparison

Map<String, Integer> map = new HashMap<>();
map.put("a", 1);
map.put("b", 2);
map.put("c", 3);
map = Collections.unmodifiableMap(map);
Map<String, Integer> map =
    Map.of("a", 1, "b", 2, "c", 3);

Why the modern way wins

๐Ÿ“

Inline creation

No temporary mutable map needed.

๐Ÿ”’

Immutable result

The map cannot be modified after creation.

๐Ÿšซ

No null keys/values

Null entries are rejected immediately.

Old Approach

Map Builder Pattern

JDK Support

Immutable map creation

Available

Widely available since JDK 9 (Sept 2017)

How it works

Map.of() accepts key-value pairs inline and returns an immutable map. For more than 10 entries, use Map.ofEntries() with Map.entry() pairs.

Related Documentation

Proof