How to Initialize Map with Key-Value Pairs in Java
How can we initialize a Map with some key-value pairs?
Suppose we want to initialize the following Map with some values.
Map<String, Integer> map;
1. Using Map.of() and Map.ofEntries() (Java 9)
If we’re using Java 9+, we can use Map.of() for up to 10 entries.
Map<String, Integer> map = Map.of(
"a", 1,
"b", 2
);
We can also use Map.ofEntries() for no limits.
Map<String, Integer> map = Map.ofEntries(
Map.entry("a", 1),
Map.entry("b", 2)
);
2. Using anonymous subclass (Java 8)
If we’re using Java 8+, we can use an anonymous subclass to initialize the map with key-value pairs.
Map<String, Integer> map = new HashMap<>() {{
put("a", 1);
put("b", 2);
}};
This is a shortened version of the normal Map initialization.
Map<String, Integer> map = new HashMap<>();
map.put("a", 1);
map.put("b", 2);
Note that using an anonymous subclass creates an entirely new class inheriting from
HashMap, thereby increasing memory consumption and start-up time.
3. Using Streams (Java 8)
We can also use the Stream API in Java 8.
Map<String, Integer> map =
Stream.of(
new SimpleEntry<>("a", 1),
new SimpleEntry<>("b", 2)
)
.collect(
Collectors.toMap(
SimpleEntry::getKey,
SimpleEntry::getValue
)
);
Read about how to create specific Map implementations from streams.
4. Using ImmutableMap.of() (Guava)
If using Guava, we can create immutable maps using ImmutableMap.of().
This will work for up to 5 key-value pairs.
Map<String, Integer> map = ImmutableMap.of("a", 1, "b", 2);
For no limits, we can use its builder:
Map<String, Integer> map = ImmutableMap.<String, Integer>builder()
.put("a", 1)
.put("b", 2)
...
.build();
Note that
ImmutableMap != HashMap.ImmutableMapfails onnullvalues, whereasHashMapdoes not.
5. Using static initializer
If our map is a class variable, we can place the initialization inside a static initializer.
static Map<String, Integer> map = new HashMap<>();
static {
map.put("a", 1);
map.put("b", 2);
}
6. Using Collections.singletonMap()
If we know our map will only have a single key-value pair, we can use Collections.singletonMap() to create an immutable map.
Map<String, Integer> map = Collections.singletonMap("a", 1);