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

This question already has an answer here:

  • How can I initialise a static Map? 40 answers

  • No, you will have to add all the elements manually. You can use a static initializer though:

    public class Demo
    {
        private static final Map<String, String> myMap;
        static
        {
            myMap = new HashMap<String, String>();
            myMap.put("a", "b");
            myMap.put("c", "d");
        }
    }
    

    Note that using a function for initialization will do the same but may improve readability of the code:

    public class Demo
    {
        private static final Map<String, String> myMap = createMap();
        private static Map<String, String> createMap()
        {
            Map<String,String> myMap = new HashMap<String,String>();
            myMap.put("a", "b");
            myMap.put("c", "d");
            return myMap;
        }
    }
    

    Java 9

    In Java 9 a couple of factory-methods are added that can also be used to simplify the creation of maps:

    public class Demo {
        private static final Map<String, String> test = Map.of("a", "b", "c", "d");
        private static final Map<String, String> test2 = Map.ofEntries(
            entry("a", "b"),
            entry("c", "d")
        );
    }
    

    In the example above both test and test2 will be the same, just with different ways of expressing the Map. The Map.of method is defined for up to ten elements in the map, while the Map.ofEntries method will have no such limit.

    Note that in this case the resulting map will be an immutable map. If you want the map to be mutable, you could copy it again, eg using mutableMap = new HashMap<>(Map.of("a", "b"));

    (See also JEP 269 and the Javadoc)


    This is one way.

    HashMap<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);
    

    If you allow 3rd party libs you can use Guava's ImmutableMap to achieve literal-like brevity:

    Map<String, String> test = ImmutableMap.of("k1", "v1", "k2", "v2");
    

    This works for up to 5 key/value pairs, otherwise you can use its builder:

    Map<String, String> test = ImmutableMap.<String, String>builder()
        .put("k1", "v1")
        .put("k2", "v2")
        ...
        .build();
    


  • note that Guava's ImmutableMap implementation differs from Java's HashMap implementation (most notably it is immutable and does not permit null keys/values)
  • for more info see Guava's user guide article on its immutable collection types
  • 链接地址: http://www.djcxy.com/p/2966.html

    上一篇: 遍历对象属性

    下一篇: 如何直接初始化一个HashMap(以字面的方式)?