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

后端 未结 14 2374
野趣味
野趣味 2020-11-22 10:58

Is there some way of initializing a Java HashMap like this?:

Map test = 
    new HashMap{\"test\":\"test\",\"test\         


        
相关标签:
14条回答
  • 2020-11-22 11:41

    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.

    0 讨论(0)
  • 2020-11-22 11:43

    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");
    
    0 讨论(0)
提交回复
热议问题