There are utility methods to create ImmutableMap
like Immutable.of(Key, value)
and its overload.
But such methods don\'t exist for
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.
Try Maps.newHashMap(ImmutableMap.of(...))
Maps.newHashMap(Map map)
cannot you use the copyOf
method of ImmutableMap
described here?
it should be something like
Map newImmutableMap = ImmutableMap.copyOf(yourMap);
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();
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.