What is the best practices to merge two maps(合并两张地图的最佳做法是什么)
问题描述
如何将新地图添加到现有地图.这些地图具有相同的类型 Map
.如果新地图的键存在于旧地图中,则应添加值.
How can I add a new map to existing map. The maps have the same type Map<String, Integer>
. If the key from new map exists in the old map the values should be added.
Map<String, Integer> oldMap = new TreeMap<>();
Map<String, Integer> newMap = new TreeMap<>();
//Data added
//Now what is the best way to iterate these maps to add the values from both?
推荐答案
通过添加,我假设您想要添加整数值,而不是创建 Map
.
By add, I assume you want to add the integer values, not create a Map<String, List<Integer>>
.
在 java 7 之前,您必须按照@laune 显示的那样进行迭代(对他+1).否则使用 java 8,Map 上有一个合并方法.所以你可以这样做:
Before java 7, you'll have to iterate as @laune showed (+1 to him). Otherwise with java 8, there is a merge method on Map. So you could do it like this:
Map<String, Integer> oldMap = new TreeMap<>();
Map<String, Integer> newMap = new TreeMap<>();
oldMap.put("1", 10);
oldMap.put("2", 5);
newMap.put("1", 7);
oldMap.forEach((k, v) -> newMap.merge(k, v, (a, b) -> a + b));
System.out.println(newMap); //{1=17, 2=5}
它所做的是对于每个键值对,它合并键(如果它还没有在 newMap
中,它只是创建一个新的键值对,否则它会更新之前的值通过添加两个整数来保持现有密钥)
What it does is that for each key-value pair, it merges the key (if it's not yet in newMap
, it simply creates a new key-value pair, otherwise it updates the previous value hold by the existing key by adding the two Integers)
另外,也许您应该考虑使用 Map<String, Long>
以避免两个整数相加时溢出.
Also maybe you should consider using a Map<String, Long>
to avoid overflow when adding two integers.
这篇关于合并两张地图的最佳做法是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:合并两张地图的最佳做法是什么


- 转换 ldap 日期 2022-01-01
- 如何指定 CORS 的响应标头? 2022-01-01
- 未找到/usr/local/lib 中的库 2022-01-01
- java.lang.IllegalStateException:Bean 名称“类别"的 BindingResult 和普通目标对象都不能用作请求属性 2022-01-01
- 如何使 JFrame 背景和 JPanel 透明且仅显示图像 2022-01-01
- GC_FOR_ALLOC 是否更“严重"?在调查内存使用情况时? 2022-01-01
- Eclipse 的最佳 XML 编辑器 2022-01-01
- 将 Java Swing 桌面应用程序国际化的最佳实践是什么? 2022-01-01
- 在 Java 中,如何将 String 转换为 char 或将 char 转换 2022-01-01
- 获取数字的最后一位 2022-01-01