This question already has an answer here:
- How can I initialise a static Map? 41 answers
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.
No, you will have to add all the elements manually. You can use a static initializer though:
Note that using a function for initialization will do the same but may improve readability of the code:
Java 9
In Java 9 a couple of factory-methods are added that can also be used to simplify the creation of maps:
In the example above both
test
andtest2
will be the same, just with different ways of expressing the Map. TheMap.of
method is defined for up to ten elements in the map, while theMap.ofEntries
method 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"));
(See also JEP 269 and the Javadoc)
There is no direct way to do this - Java has no Map literals (yet - I think they were proposed for Java 8).
Some people like this:
This creates an anonymous subclass of HashMap, whose instance initializer puts these values. (By the way, a map can't contain twice the same value, your second put will overwrite the first one. I'll use different values for the next examples.)
The normal way would be this (for a local variable):
If your
test
map is an instance variable, put the initialization in a constructor or instance initializer:If your
test
map is a class variable, put the initialization in a static initializer:If you want your map to never change, you should after the initialization wrap your map by
Collections.unmodifiableMap(...)
. You can do this in a static initializer too:(I'm not sure if you can now make
test
final ... try it out and report here.)This is one way.
However, you should be careful and make sure that you understand the above code (it creates a new class that inherits from HashMap). Therefore, you should read more here: http://www.c2.com/cgi/wiki?DoubleBraceInitialization , or simply use Guava:
An alternative, using plain Java 7 classes and varargs: create a class
HashMapBuilder
with this method:Use the method like this:
If you allow 3rd party libs, you can use Guava's ImmutableMap to achieve literal-like brevity:
This works for up to 5 key/value pairs, otherwise you can use its builder: