合并两张地图的最佳做法是什么? [英] What is the best practices to merge two maps

查看:158
本文介绍了合并两张地图的最佳做法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将新地图添加到现有地图。地图具有相同的类型 Map< String,Integer> 。如果新地图中的密钥存在于旧地图中,则应添加值。

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< String,List< Integer>>

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.

这篇关于合并两张地图的最佳做法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆