How would you initialise a static Map
in Java?
Method one: static initialiser
Method two: instance initialiser (anonymous subclass)
or
some other m
Because Java does not support map literals, map instances must always be explicitly instantiated and populated.
Fortunately, it is possible to approximate the behavior of map literals in Java using factory methods.
For example:
public class LiteralMapFactory {
// Creates a map from a list of entries
@SafeVarargs
public static Map mapOf(Map.Entry... entries) {
LinkedHashMap map = new LinkedHashMap<>();
for (Map.Entry entry : entries) {
map.put(entry.getKey(), entry.getValue());
}
return map;
}
// Creates a map entry
public static Map.Entry entry(K key, V value) {
return new AbstractMap.SimpleEntry<>(key, value);
}
public static void main(String[] args) {
System.out.println(mapOf(entry("a", 1), entry("b", 2), entry("c", 3)));
}
}
Output:
{a=1, b=2, c=3}
It is a lot more convenient than creating and populating the map an element at a time.