Search code examples
javahashmapguavabuilderimmutable-collections

ImmutableMap.Builder from a HashMap


I have a HashMap<K,V> of defaults values per keys.

I want to convert it to an ImmutableMap.Builder As I have another ImmutableMap which I want to merge and override into the original HashMap. I want to override some of the default pairs and eventually build a ImmutableMap.

How can I convert the HashMap to ImmutableMap.Builder?

I haven't seen ImmutableMap.Builder constructor that gets a HashMap.


Solution

  • Simply use putAll or am I missing something here? You cannot modify existing keys while building, but you can add more:

        Map<String, String> srcMap = Map.of("A", "a", "B", "b", "C", "c");
    
        ImmutableMap<String, String> map = ImmutableMap.<String, String> builder()
                .putAll(srcMap)
                .put("D", "d")
                .build();
    
        map.forEach((k,v) -> System.out.printf ("[%s:%s]", k, v));
    

    You could modify the srcMap itself before you invoke putAll if you want to override the existing values.

    Also, if you have a HashMap that is ready to be converted to an ImmutableMap, you can skip the builder part and just use copyOf:

    ImmutableMap<String, String> finalMap = ImmutableMap.copyOf(srcMap);