Uts*_*sav 2 java collections comparison hashmap
嗨,我正在使用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
Run Code Online (Sandbox Code Playgroud)
在比较这两个哈希映射之后,我得到的hashmap将包含Key作为First HashMap1的值,Value作为第二个HashMap2的值.
HashMap3:
Key: SAPF Value: Data1
Key: SAPL Value: Data2
Run Code Online (Sandbox Code Playgroud)
只需迭代键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));
}
}
Run Code Online (Sandbox Code Playgroud)