gpt4 book ai didi

java - 如何在 Java 中比较两个 HashMap

转载 作者:行者123 更新时间:2023-12-02 09:44:01 24 4
gpt4 key购买 nike

嗨,我正在 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com