Search code examples
javacollectionsguava

builder for HashMap


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

Solution

  • Since Java 9 Map interface contains:

    • Map.of(k1,v1, k2,v2, ..)
    • Map.ofEntries(Map.entry(k1,v1), Map.entry(k2,v2), ..).

    Limitations of those factory methods are that they:

    • can't hold nulls as keys and/or values (if you need to store nulls take a look at other answers)
    • produce immutable maps

    If we need mutable map (like HashMap) we can use its copy-constructor and let it copy content of map created via Map.of(..)

    Map<Integer, String> map = new HashMap<>( Map.of(1,"a", 2,"b", 3,"c") );