作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
嗨,我正在 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
比较这两个 HashMap 后,我生成的 HashMap 将包含作为第一个 HashMap1 的值的键和作为第二个 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));
}
}
关于java - 如何在 Java 中比较两个 HashMap ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26903891/
我是一名优秀的程序员,十分优秀!