How can I initialise a static Map?

前端 未结 30 1529
慢半拍i
慢半拍i 2020-11-22 08:43

How would you initialise a static Map in Java?

Method one: static initialiser
Method two: instance initialiser (anonymous subclass) or some other m

30条回答
  •  情深已故
    2020-11-22 09:31

    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.

提交回复
热议问题