builder for HashMap

Elazar Leibovich picture Elazar Leibovich · Sep 8, 2011 · Viewed 102.1k times · Source

Guava provides us with great factory methods for Java types, such as Maps.newHashMap().

But are there also builders for java Maps?

HashMap<String,Integer> m = Maps.BuildHashMap.
    put("a",1).
    put("b",2).
    build();

Answer

Sean Patrick Floyd picture Sean Patrick Floyd · Sep 8, 2011

There is no such thing for HashMaps, but you can create an ImmutableMap with a builder:

final Map<String, Integer> m = ImmutableMap.<String, Integer>builder().
      put("a", 1).
      put("b", 2).
      build();

And if you need a mutable map, you can just feed that to the HashMap constructor.

final Map<String, Integer> m = Maps.newHashMap(
    ImmutableMap.<String, Integer>builder().
        put("a", 1).
        put("b", 2).
        build());