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

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

问题描述

如何将新地图添加到现有地图.这些地图具有相同的类型 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.

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

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