ImmutableMap.of() workaround for HashMap in Maps?

Premraj picture Premraj · May 10, 2011 · Viewed 50.2k times · Source

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.

Answer

Jesper picture Jesper · May 10, 2011

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