ImmutableMap.of() workaround for HashMap in Maps?

前端 未结 5 793
独厮守ぢ
独厮守ぢ 2020-12-29 03:40

There are utility methods to create ImmutableMap like Immutable.of(Key, value) and its overload.

But such methods don\'t exist for

5条回答
  •  醉酒成梦
    2020-12-29 04:15

    Why would you want those for a regular HashMap or LinkedHashMap? You can just do this:

    Map map = Maps.newHashMap();
    map.put(key, value);
    

    The thing with ImmutableMap is that it is a little bit more cumbersome to create; you first need to make a Builder, then put the key-value pairs in the builder and then call build() on it to create your ImmutableMap. The ImmutableMap.of() method makes it shorter to write if you want to create an ImmutableMap with a single key-value pair.

    Consider what you'd have to write if you wouldn't use the ImmutableMap.of() method:

    ImmutableMap map = ImmutableMap.builder()
        .put(key, value);
        .build();
    

提交回复
热议问题