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

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

问题描述

我有两个地图的键是 String s,其值为 Set< MyObject> 。给定两个 Map s,最简单的方法是合并它们,以便如果两个键是相同的,则该值是两个集合的并集。你可以假定值从不为空,如果它是有用的,我们可以使这些 Map s SortedMap s。 p>

解决方案

我们在谈论 HashMap 实例。在这种情况下,查找是O(1),因此您可以只需一张地图,迭代该地图的条目,查看其他地图是否包含该密钥。如果没有,只需添加该集合。如果它包含密钥,请采取两个集合的联合(由将一个集合的所有元素添加到另一个集合)



为了说明一些代码,我使用了一个集合在我的IDE中有自动完成

  Map< String,Set&Double>> firstMap = new HashMap< String,Set&Double>(( 
映射< String,Set&Double>> secondMap = new HashMap< String,Set&Double>((
设置< 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());
}
}


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.

解决方案

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)

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天全站免登陆