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

后端 未结 14 2553
野趣味
野趣味 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 h = new HashMap() {{
        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 left = ImmutableMap.of("a", 1, "b", 2, "c", 3);
    

    ImmutableMap.of works for up to 5 entries. Otherwise, use the builder: source.

提交回复
热议问题