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

后端 未结 14 2597
野趣味
野趣味 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:38

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

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

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

    Map test = ImmutableMap.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

提交回复
热议问题