In Java, while there’s no direct “literal” syntax for initializing a HashMap like in some other languages (e.g., Python or JavaScript), you can use initialization techniques to achieve a concise, one-liner approach. Here are the most common methods:
1. Java 9+ Map.of() or Map.ofEntries() (Immutable Maps)
For immutable maps (fixed key-value pairs), use Java 9’s factory methods:
For small maps (up to 10 entries):
Map<String, Integer> map = Map.of(
"apple", 1,
"banana", 2,
"cherry", 3
);
For larger maps (using Map.ofEntries()):
import static java.util.Map.entry;
Map<String, Integer> map = Map.ofEntries(
entry("apple", 1),
entry("banana", 2),
entry("cherry", 3)
);
2. Initialize and Populate a Mutable HashMap
If you need a mutable HashMap, combine Map.of() with the HashMap constructor:
Map<String, Integer> mutableMap = new HashMap<>(Map.of(
"apple", 1,
"banana", 2
));
3. Double Brace Initialization (Legacy Approach)
⚠️ Not recommended for production code (creates anonymous classes, may cause memory leaks):
Map<String, Integer> map = new HashMap<>() {{
put("apple", 1);
put("banana", 2);
}};
4. Traditional Initialization (Explicit put())
Most compatible (works in all Java versions):
Map<String, Integer> map = new HashMap<>();
map.put("apple", 1);
map.put("banana", 2);
Key Notes
| Method | Mutability | Java Version | Use Case |
|---|---|---|---|
Map.of()/Map.ofEntries | Immutable | 9+ | Simple, fixed key-value pairs |
new HashMap<>(Map.of()) | Mutable | 9+ | Mutable maps with initial values |
| Double Brace | Mutable | All | Quick prototyping (not recommended) |
Explicit put() | Mutable | All | Most flexible, verbose |
Example: Mutable HashMap with Java 8+
import java.util.HashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
map.put("apple", 1);
map.put("banana", 2);
System.out.println(map); // {banana=2, apple=1}
}
}
Recommendation
- Java 9+: Use
Map.ofEntries()for immutable maps or wrap withnew HashMap<>()for mutability. - Java 8 and below: Use the explicit
put()method or utility methods from libraries like Guava.
For large datasets, consider using a loop or streaming API to populate the map dynamically.