Immutable map creation
Create immutable maps inline without a builder.
Porównanie kodu
✕ Java 8
Map<String, Integer> map = new HashMap<>();
map.put("a", 1);
map.put("b", 2);
map.put("c", 3);
map = Collections.unmodifiableMap(map);
✓ Java 9+
Map<String, Integer> map =
Map.of("a", 1, "b", 2, "c", 3);
Widzisz problem z tym kodem? Daj nam znać.
Dlaczego nowoczesne podejście wygrywa
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.
Stare podejście
Map Builder Pattern
Nowoczesne podejście
Map.of()
Od JDK
9
Poziom trudności
Początkujący
Wsparcie JDK
Immutable map creation
Dostępne
Widely available since JDK 9 (Sept 2017)
Jak to działa
Map.of() accepts key-value pairs inline and returns an immutable map. For more than 10 entries, use Map.ofEntries() with Map.entry() pairs.
Powiązana dokumentacja