如何比较 Java 中的两个哈希映射
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26903891/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to compare two Hash Maps in Java
提问by Utsav
Hi I am working with HashMap in java and i have a scenario where i have to compare 2 HashMaps
嗨,我正在 Java 中使用 HashMap,我有一个场景,我必须比较 2 个 HashMap
HashMap1:
Key: BOF Value: SAPF
Key: BOM Value: SAPM
Key: BOL Value: SAPL
HashMap2:
Key: BOF Value: Data1
Key: BOL Value: Data2
And after comparing these two hashmaps my resulting hashmap will contain the Key as a Value of First HashMap1 and Value as a Value of second HashMap2.
在比较这两个散列图之后,我得到的散列图将包含作为第一个 HashMap1 的值的键和作为第二个 HashMap2 的值的值。
HashMap3:
Key: SAPF Value: Data1
Key: SAPL Value: Data2
采纳答案by Florent Bayle
Just iterate on the keys of HashMap1
, and for each key, check if it's present in HashMap2
.
If it's present, add the values to HashMap3
:
只需迭代 的键HashMap1
,对于每个键,检查它是否存在于HashMap2
. 如果存在,请将值添加到HashMap3
:
final Map<String, String> hm1 = new HashMap<String, String>();
hm1.put("BOF", "SAPF");
hm1.put("BOM", "SAPM");
hm1.put("BOL", "SAPL");
final Map<String, String> hm2 = new HashMap<String, String>();
hm2.put("BOF", "Data1");
hm2.put("BOL", "Data2");
final Map<String, String> hm3 = new HashMap<String, String>();
for (final String key : hm1.keySet()) {
if (hm2.containsKey(key)) {
hm3.put(hm1.get(key), hm2.get(key));
}
}
回答by jjlema
You can use the keySets of both maps to intersect them using:
您可以使用两个地图的 keySets 将它们相交:
boolean retainAll(Collection<?> c)
and then iterate using that intersection over the tho maps building your solution.
然后在构建解决方案的 tho 地图上使用该交集进行迭代。
回答by Udo
Iterate over the keys of the first map and put the values in your new map, if the second map has a value for the same key.
如果第二个映射具有相同键的值,则迭代第一个映射的键并将值放入新映射中。
Map map3 = new HashMap();
for (Object key : map1.keySet()) {
Object value2 = map2.get(key);
if (value2 != null) {
Object value1 = map1.get(key);
map3.put(value1, value2);
}
}
回答by Persixty
HashMap has an method called entrySet()
that returns an object that represents the content of the map as a set of key-value pairs.
HashMap 有一个被调用的方法entrySet()
,该方法返回一个对象,该对象将映射的内容表示为一组键值对。
public Set<Map.Entry<K,V>> entrySet()
You should iterate through that set using the keys to look up in the second map and then putting the results in the 'result set'.
您应该使用键遍历该集合以在第二个映射中查找,然后将结果放入“结果集”中。
I assume you have a established that the valuesin the first set will be unique OR you don't mind that entries might get overwritten in the output.
我假设您已经确定第一组中的值将是唯一的,或者您不介意输出中的条目可能会被覆盖。
Notice that the iterator moves through the set in an unspecified order so if there are overwrites this method won't guarantee which values overwrite which other values.
请注意,迭代器以未指定的顺序在集合中移动,因此如果存在覆盖,则此方法无法保证哪些值会覆盖哪些其他值。