Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

How to directly initialize a HashMap (in a literal way)?

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 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.
by

2 Answers

RoliMishra
For Java Version 9 or higher versions*

// this works for up to 10 elements:
Map<String, String> test1 = Map.of(
"a", "b",
"c", "d"
);

// this works for any number of elements:
import static java.util.Map.entry;
Map<String, String> test2 = Map.ofEntries(
entry("a", "b"),
entry("c", "d")
);


*For up to java 8 versions


Map<String, String> myMap = new HashMap<String, String>() {{
put("a", "b");
put("c", "d");
}};
kshitijrana14
This is one way.

Map<String, String> h = new HashMap<String, String>() {{
put("a","b");
}};

Login / Signup to Answer the Question.