> 在Java中,java,hashmap"/>

首页 > 解决方案 > 合并 2 个地图> 在Java中

问题描述

我有 2 个 HashMap

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"}}

我试过 putAll() 但这会覆盖这些值。

标签: javahashmap

解决方案


您确实使用putAll(),但在内部地图上,而不是外部地图上。

以下实现不需要 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
}

在重复产品的情况下,Product来自map2将获胜。


推荐阅读