java - 如果键匹配,则为哈希图列表添加值
问题描述
我有一个哈希图列表。所有值都是整数。我想根据键匹配添加所有值。
假设我有一张像这样的地图:
Map<String, Integer> map1 = new HashMapMap<String, Integer>();
map1.put("RE", 14);
map1.put("SE", 15);
map1.put("DE", 13);
Map<String, Integer> map2 = new HashMapMap<String, Integer>();
map2.put("RE", 11);
map2.put("SE", 10);
map2.put("DE", 11);
Map<String, Integer> map3 = new HashMapMap<String, Integer>();
map3.put("RE", 1);
map3.put("SE", 2);
Map<String, Integer> map4 = new HashMapMap<String, Integer>();
map4.put("RE", 6);
map4.put("SE", 7);
map4.put("DE", 8);
现在我需要一张地图作为输出
Map<String, Integer> output= new HashMapMap<String, Integer>();
output.put("RE", 32);
output.put("SE", 24);
output.put("DE", 32);
解决方案
如果您有一个哈希映射列表,那么您需要遍历每个哈希映射并将值添加/更新到您的输出哈希映射。像这样:
public static void main(String[] args) {
HashMap<String, Integer> map1 = new HashMap<>();
HashMap<String, Integer> output = new HashMap<>();
for (Map.Entry<String, Integer> mapItem : map1.entrySet()) {
if (!output.containsKey(mapItem.getKey())) {
output.put(mapItem.getKey(), mapItem.getValue());
} else {
output.put(mapItem.getKey(), output.get(mapItem.getKey()) + mapItem.getValue());
}
}
}
推荐阅读
- google-apps-script - 在 Google 表格中将持续时间从文本转换为时间值(例如 2 小时 15 分钟到 2 小时 15 分 0 秒)
- javascript - .Splice() 方法无法正常工作 - 我在这里缺少什么?
- reactjs - 创建行为异常加载环境变量的 React App
- elasticsearch - Garbage in Garbage out 处理策略
- flutter - 颤振设置状态,如 instagram 帖子
- sql - 尽管函数定义中有 RETURN 语句,但 Postgres 查询没有结果数据的目的地
- if-statement - Makefile:根据安装的内容选择值
- javascript - 如何模拟波动方程
- ffmpeg - FFmpeg 命令行参数跳过视频中的第 n 帧而不读取 0..(n-1)
- dpkg - 突触报告已安装软件包的计数不正确?