How would you initialise a static Map in Java?
Method one: static initialiser
Method two: instance initialiser (anonymous subclass)
or
some other m
Here's my favorite when I don't want to (or cannot) use Guava's ImmutableMap.of(), or if I need a mutable Map:
public static Map asMap(Object... keysAndValues) {
return new LinkedHashMap() {{
for (int i = 0; i < keysAndValues.length - 1; i++) {
put(keysAndValues[i].toString(), (A) keysAndValues[++i]);
}
}};
}
It's very compact, and it ignores stray values (i.e. a final key without a value).
Usage:
Map one = asMap("1stKey", "1stVal", "2ndKey", "2ndVal");
Map two = asMap("1stKey", Boolean.TRUE, "2ndKey", new Integer(2));