简体   繁体   English

如何比较两个哈希图以查看键是否相等?

[英]How can I compare two hashmaps to see if the keys are equal?

I have two hashmaps let's say hashmap1 and hashmap2 so that hashmap2 contains common keys with hashmap1 .我有两个 hashmap 比方说hashmap1hashmap2以便hashmap2包含与hashmap1公共键。 So, I want to check that if the keys are common or equal in both hashmaps, then I multiply the values of hashmap2 by 2 in each iteration.因此,我想检查两个哈希图中的键是否相同或相等,然后在每次迭代hashmap2的值乘以 2。

My code is as follows but it gives me zero.我的代码如下,但它给了我零。 Actually, I want to practice the operation otherwise I can easily multiply the values of hashmap2 without comparing with hashmap1 .实际上,我想练习该操作,否则我可以轻松地将hashmap2的值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);

Moreover, the keys for hashmaps are String此外,hashmap 的键是String

First of all, you initialize mult with zero, so every time you multiply by zero, you get zero.首先,你用零初始化mult ,所以每次乘以零,你就会得到零。

Regarding your question, you should do hashmap1.keySet().equals(hashmap2.keySet()) to check if two sets are equal.关于你的问题,你应该做hashmap1.keySet().equals(hashmap2.keySet())来检查两个集合是否相等。

You can use the following code for this您可以为此使用以下代码

    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);
                }
            }
        }
    }

Hope the below code resolve your issue希望以下代码可以解决您的问题

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));
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM