2

I have two hashmaps let's say hashmap1 and hashmap2 so that hashmap2 contains common keys with 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.

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.

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

Hami
  • 101
  • 2
  • 8
  • Can you show some sample inputs and outputs? – Sweeper Mar 05 '20 at 11:04
  • I don't think you can compare the return of keyset() with ==, it will just check if that's the same object (which won't be the case) – baudsp Mar 05 '20 at 11:05
  • Does this answer your question? [What is the fastest way to compare two sets in Java?](https://stackoverflow.com/questions/3341202/what-is-the-fastest-way-to-compare-two-sets-in-java) – Guy Mar 05 '20 at 11:06

3 Answers3

2

First of all, you initialize mult with zero, so every time you multiply by zero, you get zero.

Regarding your question, you should do hashmap1.keySet().equals(hashmap2.keySet()) to check if two sets are equal.

2

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);
                }
            }
        }
    }
P Mittal
  • 172
  • 6
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));
        }
    }
vigneshwaran m
  • 351
  • 2
  • 12