C# to Java - Dictionaries?

后端 未结 5 1213
伪装坚强ぢ
伪装坚强ぢ 2020-12-25 09:41

Is it possible in Java to make a Dictionary with the items already declared inside it? Just like the below C# code:

   Dictionary d = new          


        
5条回答
  •  无人及你
    2020-12-25 10:32

    If you use the Guava library, you can use its ImmutableMap class, either by itself (examples 1 and 2), or as an initializer for a HashMap (examples 3 and 4):

    Map map1 = ImmutableMap. builder()
        .put("cat", 2)
        .put("dog", 1)
        .put("llama", 0)
        .put("iguana", -1)
        .build();
    Map map2 = ImmutableMap.of(
        "cat", 2,
        "dog", 1,
        "llama", 0,
        "iguana", -1
    );
    Map map3 = Maps.newHashMap(
        ImmutableMap. builder()
        .put("cat", 2)
        .put("dog", 1)
        .put("llama", 0)
        .put("iguana", -1)
        .build()
    );
    Map map4 = Maps.newHashMap( ImmutableMap.of(
        "cat", 2,
        "dog", 1,
        "llama", 0,
        "iguana", -1)
    );
    

提交回复
热议问题