java - 合并 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() 但这会覆盖这些值。
解决方案
您确实使用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
将获胜。
推荐阅读
- java - 将两个没有值的 json 响应与 Jackson 进行比较
- css - 使用具有不同父级的 SASS 混合的增量转换延迟
- python - Python - 不可靠的 shell 命令执行?运行 ir-ctl 命令时出现问题
- rust - 当它说“允许在没有 RAII 保护对象的情况下进行原始(解锁)锁定”时,parking_lot 文档是什么意思?
- python - 在python Dataframe中附加单词出现的计数
- c++ - C++ 存储和更新已排序项目的有效方法
- terminal - 在 Mac OSX Sierra 上使用 Homebrew 安装 gedit
- windows - 如何在 Windows 10 的音乐中编辑 MP3、FLAC 等文件的标题、贡献艺术家、专辑、年份等信息
- asp.net-web-api - 有没有办法从同一网络的多个设备中检索 cookie?
- assembly - 当我在 C 中调用 ASM 函数时,参数不会出现在堆栈上