Is there some way of initializing a Java HashMap like this?:
Map<String,String> test =
new HashMap<String, String>{"test":"test","test":"test"};
What would be the correct syntax? I have not found anything regarding this. Is this possible? I am looking for the shortest/fastest way to put some “final/static” values in a map that never change and are known in advance when creating the Map.
All Versions
In case you happen to need just a single entry: There is
Collections.singletonMap("key", "value").For Java Version 9 or higher:
Yes, this is possible now. In Java 9 a couple of factory methods have been added that simplify the creation of maps :
In the example above both
testandtest2will be the same, just with different ways of expressing the Map. TheMap.ofmethod is defined for up to ten elements in the map, while theMap.ofEntriesmethod will have no such limit.Note that in this case the resulting map will be an immutable map. If you want the map to be mutable, you could copy it again, e.g. using
mutableMap = new HashMap<>(Map.of("a", "b"));. Also note that in this case keys and values must not benull.(See also JEP 269 and the Javadoc)
For up to Java Version 8:
No, you will have to add all the elements manually. You can use an initializer in an anonymous subclass to make the syntax a little bit shorter:
However, the anonymous subclass might introduce unwanted behavior in some cases. This includes for example:
Using a function for initialization will also enable you to generate a map in an initializer, but avoids nasty side-effects: