嗨,我正在使用Java中的HashMap,我有一个场景,我必须比较2个HashMaps
HashMap1:
Key: BOF Value: SAPF
Key: BOM Value: SAPM
Key: BOL Value: SAPL
HashMap2:
Key: BOF Value: Data1
Key: BOL Value: Data2
在比较了这两个哈希图之后,我得到的哈希图将包含Key作为First HashMap1的值和Value作为Second HashMap2的值。
HashMap3:
Key: SAPF Value: Data1
Key: SAPL Value: 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));
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句