合并两个地图 [英] Merging two Maps

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

问题描述

我有两个映射,它们的键是 Strings,它们的值是 Set.给定两个 Map ,合并它们的最简单方法是什么,如果两个键相同,则值是两个集合的并集.你可以假设值永远不会为空,如果它有用,我们可以制作这些 Maps SortedMaps.

I have two maps whose keys are Strings and whose values are Set<MyObject>. Given two Maps, what is the easiest way to merge them such that if two keys are identical, the value is a union of the two sets. You can assume values are never null and if it is useful, we can make these Maps SortedMaps.

推荐答案

我们在谈论 HashMap 实例吗?在这种情况下,查找是 O(1),因此您可以只获取一个映射,迭代该映射的条目,查看另一个映射是否包含该键.如果没有,只需添加集合.如果它包含密钥,则取两个集合的并集(通过 将一个集合的所有元素添加到另一个集合中)

Are we talking about HashMap instances. In that case lookup is O(1), so you can just take one map, iterate over the entries of that map, see whether the other map contains that key. If not, just add the set. If it contains the key, take the union of the two sets (by adding all elements of one set to another)

用一些代码来说明,我使用 Set 在我的 IDE 中自动完成

To illustrate with some code, where I used a Set to have autocompletion in my IDE

Map<String, Set<Double>> firstMap = new HashMap<String, Set<Double>>(  );
Map<String, Set<Double>> secondMap = new HashMap<String, Set<Double>>(  );
Set<Map.Entry<String, Set<Double>>> entries = firstMap.entrySet();
for ( Map.Entry<String, Set<Double>> entry : entries ) {
  Set<Double> secondMapValue = secondMap.get( entry.getKey() );
  if ( secondMapValue == null ) {
    secondMap.put( entry.getKey(), entry.getValue() );
  }
  else {
    secondMapValue.addAll( entry.getValue() );
  }
}

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

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