kuhan
kuhan

Reputation: 11

merge 2 maps Map<Enum, Map<String,Object>> in java

i have 2 HashMaps

Map<ProductType, Map<String, Product>> map1;
Map<ProductType, Map<String, Product>> map2;

class Product {
private string id; // a unique key of 32 digit alpha numberic charaters
}

map1 --> "Type1" : {{"P1":"423432423"},{"P2":"tertertr35432"}}
map2 --> "Type1" : {{"P3":"423467865832423"},{"P4":"tert89789ertr35432"}}
         "Type2" : {{"P5":"4978965832423"}}

result -> "Type1" : {{"P1":"423432423"},{"P2":"tertertr35432"},{"P3":"423467865832423"},{"P4":"tert89789ertr35432"}}
           Type2" : {{"P5":"4978965832423"}}

I tried putAll() but that's overriding the values.

Upvotes: 0

Views: 237

Answers (1)

Andreas
Andreas

Reputation: 159096

You do use putAll(), but on the inner map, not the outer map.

The following implementation does not require Java 8.

Map<ProductType, Map<String, Product>> map3 = new HashMap<>();
for (Map.Entry<ProductType, Map<String, Product>> e : map1.entrySet())
    map3.put(e.getKey(), new HashMap<>(e.getValue())); // Copy inner map
for (Map.Entry<ProductType, Map<String, Product>> e : map2.entrySet()) {
    Map<String, Product> inner = map3.get(e.getKey());
    if (inner == null)
        map3.put(e.getKey(), new HashMap<>(e.getValue())); // Copy inner map
    else
        inner.putAll(e.getValue()); // Merge inner maps
}

In case of duplicate Products, the Product from map2 will win.

Upvotes: 1

Related Questions