开发者

ImmutableMap.of() workaround for HashMap in Maps?

开发者 https://www.devze.com 2023-03-04 16:10 出处:网络
There are utility methods to create ImmutableMap like Immutable.of(Key, value) and its overload. But such methods don\'t exist for HashMap or LinkedHashMap in Maps class.

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

But such methods don't exist for HashMap or LinkedHashMap in Maps class.

Is there any better way to do this or Guava assumes开发者_如何学编程 such a map is always a constant map and ImmutableMap is best option to go with and don't need to provide a utility for HashMap.


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();


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

Maps.newHashMap(Map map)


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.


cannot you use the copyOf method of ImmutableMap described here?

it should be something like

Map newImmutableMap = ImmutableMap.copyOf(yourMap);


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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号