How to directly initialize a HashMap (in a literal way)?
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
Java does not have a built-in HashMap literal syntax like Python's {"key": "value"}. However, there are several approaches: Map.of() and Map.ofEntries() (Java 9+, immutable), Map.entry() for type-safe entries, double-brace initialization (creates anonymous subclass, generally avoided), and static initializer blocks. For mutable maps, wrap Map.of() with new HashMap<>(Map.of(...)). The recommended approach for Java 9+ is Map.of() for small maps (up to 10 entries) and Map.ofEntries() for larger ones.
Map.of() — Java 9+ (Recommended)
Map.of() creates an unmodifiable map. It supports up to 10 key-value pairs (overloaded methods for 0 to 10 pairs). It does not allow null keys or values, and throws IllegalArgumentException for duplicate keys.
Map.ofEntries() — Java 9+ (More Than 10 Entries)
Map.ofEntries() takes Map.Entry objects and has no limit on the number of entries. Use the static import Map.entry() for concise syntax.
Mutable Map from Map.of()
new HashMap<>(Map.of(...)) creates a mutable HashMap initialized with the immutable map's entries. This is the standard pattern for a "HashMap literal" in Java 9+.
Double-Brace Initialization (Avoid)
Double-brace initialization is concise but creates a hidden anonymous subclass. This causes issues with serialization, equals() comparisons, and memory leaks. Prefer Map.of() or explicit initialization.
Static Initializer Block
Static initializer blocks are the pre-Java 9 standard for creating constant maps. Collections.unmodifiableMap() wraps the map to prevent modification.
Guava ImmutableMap (Third-Party)
Guava's ImmutableMap predates Java 9's Map.of() and offers similar functionality. If your project already uses Guava, this is a fine choice. Otherwise, prefer the standard library.
Java 8 Streams Approach
The Stream approach is verbose and not recommended for simple initialization. Use Map.of() or Map.ofEntries() instead.
Comparison Across Languages
Common Pitfalls
- Using double-brace initialization in production: It creates an anonymous inner class that holds a reference to the enclosing instance, preventing garbage collection and causing memory leaks in long-lived objects. Use
Map.of()or explicitput()calls instead. - Trying to modify
Map.of()results:Map.of()returns an unmodifiable map. Callingput(),remove(), orclear()throwsUnsupportedOperationException. Wrap innew HashMap<>()if you need a mutable map. - Passing
nulltoMap.of():Map.of()andMap.ofEntries()do not allownullkeys or values. They throwNullPointerExceptionimmediately. If you neednullvalues, use aHashMapwith explicitput()calls. - Exceeding
Map.of()limit:Map.of()supports at most 10 key-value pairs (20 arguments). For more entries, useMap.ofEntries()withentry()calls, which has no limit. - Duplicate keys in
Map.of():Map.of("a", 1, "a", 2)throwsIllegalArgumentExceptionat runtime. UnlikeHashMap.put()which silently overwrites,Map.of()treats duplicate keys as an error. Ensure all keys are unique.
Summary
- Use
Map.of("key", value, ...)for small immutable maps (up to 10 entries, Java 9+) - Use
Map.ofEntries(entry("key", value), ...)for larger immutable maps - Wrap in
new HashMap<>(Map.of(...))when you need a mutable map - Avoid double-brace initialization — it creates anonymous subclasses with memory leak risk
- Use static initializer blocks with
Collections.unmodifiableMap()for pre-Java 9 code Map.of()does not allownullkeys or values and rejects duplicate keys

