In this tutorial we explain correct ways to initialize a Java HashMap with the curly brackets like {"key1": "value1", "key2": "value2"}.
We will try to explain simple and shorter ways to put some values in a map that never change and are known in advance when crerating the Map.
Using java and no other libs
This can't be done with plain Java. You have to add all the elements with your code..
Another way is to use a static initialized. However this is not probably what you are looking for. A third party lib could help you solve in a nicer way this initializacion.
public class HashMapInit {
private static final Map myMap;
static {
myMap = new HashMap();
myMap.put("a", "b");
myMap.put("c", "d");
}
}
Using guava library
The 3rd party lib Guava has an ImmutableMap which allows to achieve literal-like brevity or similar curly brackets notation:
Map test = ImmutableMap.of("key1", "value1", "key2",
"value2");
The lib allow to have up to 5 key/value pairs which is very limited.
Another way is to use the put method like this:
Map test = ImmutableMap.builder() .put("k1", "v1") .put("k2", "v2") ...
.build();
If you need more information about HashMap implementation check:
- Guava's ImmutableMap implementation.
- Java's HashMap implementation.