ImmutableMap.of() workaround for HashMap in Maps?

前端 未结 5 760
独厮守ぢ
独厮守ぢ 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 03:55

    ImmutableMap.of() returns a hash based immutable map without order.

    If you need ordered immutable map, ImmutableSortedMap.of() is a choice.

    ImmutableSortedMap provides methods such as firstKey(), lastKey(), headMap(K) and tailMap(K);

    Both classes provide copyOf(Map) method.

    0 讨论(0)
  • 2020-12-29 03:58

    Try Maps.newHashMap(ImmutableMap.of(...))

    Maps.newHashMap(Map map)

    0 讨论(0)
  • 2020-12-29 04:06

    cannot you use the copyOf method of ImmutableMap described here?

    it should be something like

    Map newImmutableMap = ImmutableMap.copyOf(yourMap);
    
    0 讨论(0)
  • 2020-12-29 04:15

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

    Map<String, Object> 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<String, Object> map = ImmutableMap.builder()
        .put(key, value);
        .build();
    
    0 讨论(0)
  • 2020-12-29 04:15

    The difference is that for an immutable map, you have to provide everything up-front, because you can't change it after construction. For mutable maps, you can just create the map and then add the entries. Admittedly this makes it slightly harder to create a map in a single expression, but that doesn't tend to be a problem where you'd want a mutable map anyway, in my experience.

    0 讨论(0)
提交回复
热议问题