【问题标题】:How can I compare two hashmaps to see if the keys are equal?如何比较两个哈希图以查看键是否相等?
【发布时间】:2023-04-05 09:17:01
【问题描述】:

我有两个哈希图,比如说hashmap1hashmap2,所以hashmap2 包含带有hashmap1 的公共键。因此,我想检查两个哈希图中的键是否相同或相等,然后在每次迭代中将 hashmap2 的值乘以 2。

我的代码如下,但它给了我零。实际上,我想练习操作,否则我可以轻松地将hashmap2 的值相乘,而无需与hashmap1 进行比较。

double mult=2;
        for(String s:hashmap1.keySet()) {


            if(hashmap1.keySet()==hashmap2.keySet()) {

                mult= mult * hashmap1.get(s);
            }else {
                continue;
                }

            }

        System.out.println("The new values for hashmap2: " + mult);

此外,hashmaps 的键是String

【问题讨论】:

  • 你能展示一些示例输入和输出吗?
  • 我认为你不能将 keyset() 的返回值与 == 进行比较,它只会检查是否是同一个对象(不会是这种情况)

标签: java


【解决方案1】:

希望下面的代码解决您的问题

Map<String, Integer> hashMap1 = new HashMap<>();
    hashMap1.put("A", 2);
    hashMap1.put("B", 3);

    Map<String, Integer> hashMap2 = new HashMap<>();
    hashMap2.put("A", 2);
    hashMap2.put("B", 3);
    hashMap2.put("C", 4);

    for (Entry<String, Integer> entryHashMap2 : hashMap2.entrySet()) {
        if (hashMap1.containsKey(entryHashMap2.getKey())) {
        System.out.println(entryHashMap2.getValue() * 2);
        hashMap2.put(entryHashMap2.getKey(), (entryHashMap2.getValue() * 2));
        }
    }

【讨论】:

    【解决方案2】:

    首先,你用零初始化mult,所以每次乘以零,你就得到零。

    关于你的问题,你应该做hashmap1.keySet().equals(hashmap2.keySet())来检查两组是否相等。

    【讨论】:

    • 是的,当然,我将其更改为 2,但它又给了我零。我会试试你的建议
    【解决方案3】:

    您可以为此使用以下代码

        public class Main {
            public static void main(String[] args) {
                Map map1 = new HashMap<String, Integer>();
                map1.put("a", 1);
                map1.put("b", 2);
                Map map2 = new HashMap<String, Integer>();
                map2.put("a", 1);
                map2.put("b", 3);
                map2.put("c", 3);
                System.out.println(map1.keySet().equals(map2.keySet()));
                if (map1.keySet().equals(map2.keySet())) {
                    Iterator<Map.Entry<String, Integer>> iterator = map2.entrySet().iterator();
                    while (iterator.hasNext()) {
                        Map.Entry<String, Integer> entry = iterator.next();
                        map2.put(entry.getKey(), entry.getValue() * 2);
                    }
                }
            }
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-20
      相关资源
      最近更新 更多