Is there some way of initializing a Java HashMap like this?:
Map test =
new HashMap{\"test\":\"test\",\"test\
This is one way.
Map<String, String> h = new HashMap<String, String>() {{
put("a","b");
}};
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:
Map<String, Integer> left = ImmutableMap.of("a", 1, "b", 2, "c", 3);
ImmutableMap.of
works for up to 5 entries. Otherwise, use the builder: source.
With Java 8 or less
You can use static block to initialize a map with some values. Example :
public static Map<String,String> test = new HashMap<String, String>
static {
test.put("test","test");
test.put("test1","test");
}
With Java 9 or more
You can use Map.of() method to initialize a map with some values while declaring. Example :
public static Map<String,String> test = Map.of("test","test","test1","test");