How to directly initialize a Java HashMap with literal values?
What is the correct syntax for initializing a Java HashMap with predefined key-value pairs in a literal way? For example:
Map<String, String> test = new HashMap<String, String>{"test":"test","test":"test"};
Is this approach possible in Java? I’m looking for the most efficient method to create a HashMap with static/final values that are known at compile time and won’t change.
In Java, you cannot directly initialize a HashMap using literal syntax like new HashMap<String, String>{"test":"test","test":"test"} - this syntax is not valid Java. However, there are several effective ways to create HashMaps with predefined key-value pairs, with modern Java offering the most elegant solutions through immutable map factory methods introduced in Java 9.
Contents
- Java 9+ Literal Syntax
- Pre-Java 9 Static Initializers
- Third-Party Library Solutions
- Choosing the Right Approach
- Performance and Memory Considerations
- Complete Comparison
Java 9+ Literal Syntax
Java 9 introduced the Map.of() and Map.ofEntries() methods that provide the closest thing to literal syntax in Java:
Map.of() Method
For maps with 1 to 10 key-value pairs:
// Single entry
Map<String, String> single = Map.of("key", "value");
// Multiple entries (up to 10)
Map<String, String> test = Map.of(
"test1", "value1",
"test2", "value2",
"test3", "value3"
);
Map.ofEntries() Method
For maps with more than 10 entries or when you want explicit entry creation:
import static java.util.Map.entry;
Map<String, String> largeMap = Map.ofEntries(
entry("key1", "value1"),
entry("key2", "value2"),
entry("key3", "value3"),
// ... more entries
entry("key20", "value20")
);
Creating Mutable Maps from Immutable Ones
If you need a mutable HashMap, wrap the immutable map:
Map<String, String> mutableMap = new HashMap<>(Map.of(
"test1", "value1",
"test2", "value2"
));
Pre-Java 9 Static Initializers
Before Java 9, you had to use these approaches:
Static Block Initialization
public class Constants {
private static final Map<String, String> TEST_MAP;
static {
Map<String, String> temp = new HashMap<>();
temp.put("test1", "value1");
temp.put("test2", "value2");
TEST_MAP = Collections.unmodifiableMap(temp);
}
}
Double Brace Initialization (Anti-pattern)
Map<String, String> test = new HashMap<String, String>() {{
put("test1", "value1");
put("test2", "value2");
}};
Warning: Double brace initialization creates an anonymous inner class each time, which can cause memory leaks and is considered an anti-pattern.
Using Arrays and Utility Methods
private static final String[] keys = {"key1", "key2", "key3"};
private static final String[] values = {"value1", "value2", "value3"};
public static Map<String, String> createMap() {
Map<String, String> map = new HashMap<>();
for (int i = 0; i < keys.length; i++) {
map.put(keys[i], values[i]);
}
return Collections.unmodifiableMap(map);
}
Third-Party Library Solutions
Guava’s ImmutableMap
import com.google.common.collect.ImmutableMap;
Map<String, String> test = ImmutableMap.of(
"test1", "value1",
"test2", "value2"
);
Java 8 Stream API
Map<String, String> test = Stream.of(
new AbstractMap.SimpleEntry<>("test1", "value1"),
new AbstractMap.SimpleEntry<>("test2", "value2")
).collect(Collectors.toMap(
Map.Entry::getKey,
Map.Entry::getValue,
(oldVal, newVal) -> newVal,
HashMap::new
));
Choosing the Right Approach
For Java 9+ Projects
Use Map.of() or Map.ofEntries() for:
- Immutable maps: Direct syntax, compile-time safety
- Static constants: Perfect for
static finalfields - Code readability: Clean and concise
For Pre-Java 9 Projects
Use static initializers for:
- Immutable constants: Memory efficient, thread-safe
- Large maps: Better than double brace initialization
- Android development: Compatible with older Android APIs
For Mutable Maps
// Java 9+
Map<String, String> mutable = new HashMap<>(Map.of("k", "v"));
// Pre-Java 9
Map<String, String> mutable = new HashMap<>();
mutable.put("k1", "v1");
mutable.put("k2", "v2");
Performance and Memory Considerations
Memory Efficiency
- Immutable maps (
Map.of,Map.ofEntries): Share backing arrays, memory efficient - Static initializers: Initialize once at class loading time
- Double brace: Creates new anonymous class each time (memory leak risk)
Compile-Time Optimization
// This will be optimized by the JVM
private static final Map<String, String> CONSTANTS = Map.of(
"A", "1", "B", "2", "C", "3"
);
Immutable maps created with Map.of() and Map.ofEntries() are optimized by the JVM to avoid unnecessary object allocations.
Complete Comparison
| Method | Java Version | Mutability | Performance | Readability | Memory Usage |
|---|---|---|---|---|---|
Map.of() |
9+ | Immutable | Excellent | Excellent | Excellent |
Map.ofEntries() |
9+ | Immutable | Excellent | Excellent | Excellent |
| Static Block | All | Immutable | Good | Good | Good |
| Double Brace | All | Mutable | Poor | Fair | Poor |
| Guava ImmutableMap | All | Immutable | Excellent | Excellent | Good |
| Manual Creation | All | Mutable | Excellent | Poor | Good |
Best Practice Recommendation
For modern Java development (Java 9+), use Map.of() for maps with 1-10 entries and Map.ofEntries() for larger maps:
// Static final constant (immutable)
private static final Map<String, String> CONFIG = Map.of(
"host", "localhost",
"port", "8080",
"timeout", "30"
);
// Mutable map when needed
public Map<String, String> getMutableConfig() {
return new HashMap<>(CONFIG);
}
This approach provides compile-time safety, excellent performance, and clean syntax that’s closest to the literal syntax you were looking for.
Sources
- Java - How to directly initialize a HashMap (in a literal way)? - Stack Overflow
- Initialize a HashMap in Java | Baeldung
- Java 9 - How to create immutable collections using List.of, Set.of, Map.of, Map.ofEntries methods with examples - JavaBrahman
- Java 9 Immutable Map Example | Java Tutorial Network
- How to initialize a HashMap in Java - Mkyong.com
- Java Map.of() and Map.ofEntries() Example - ConcretePage
- Map (Java SE 9 & JDK 9) - Oracle Documentation
Conclusion
- Direct literal syntax like
new HashMap<String, String>{"key":"value"}is not possible in Java - Java 9+ provides the best solution with
Map.of()andMap.ofEntries()for literal-like syntax - Immutable maps are recommended for
static finalconstants due to thread safety and performance - Pre-Java 9 requires static initializers or third-party libraries like Guava
- Mutable maps can be created by wrapping immutable maps in
new HashMap<>() - Double brace initialization should be avoided due to memory leak risks and performance issues
For modern Java development, embrace the Map.of() and Map.ofEntries() methods for clean, efficient, and readable HashMap initialization.