如何在Java中比较两个Hash Map [英] How to compare two Hash Maps in Java
本文介绍了如何在Java中比较两个Hash Map的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
HashMap1:$ HashMap b $ b键:BOF值:SAPF
键:BOM值:SAPM
键:BOL值:SAPL
HashMap2:
键:BOF值:Data1
键:BOL值:Data2
在比较这两个哈希以后,我的结果hashmap将包含键作为第一个HashMap1的值和值作为第二个HashMap2的值。
HashMap3:
键:SAPF值:Data1
键:SAPL值:Data2
解决方案
只需迭代 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));
}
}
Hi I am working with HashMap in java and i have a scenario where i have to compare 2 HashMaps
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.
HashMap3:
Key: SAPF Value: Data1
Key: SAPL Value: Data2
解决方案
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
:
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));
}
}
这篇关于如何在Java中比较两个Hash Map的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文