1

I'm struggling with a little bit of code, and I just cannot figure out what the correct syntax would be. Here is an example of the problem:

for (Integer key : map1.keySet()) {

    for (Integer value : map2.values()) {

        if (value == key) {

            // ++ the corresponding value of the looping map1 key.
            // tried statements like map1.values()++  
            // but this is an invalid operation.

        }
    }
}

I am trying to loop map1 keys through map2 values and if within this process a map1 key matches a map2 value, I want to add one to the value of the corresponding map1 key.

Should be a simple problem but Eclipse keeps telling me that I have the syntax wrong, can anyone suggest what statement I may need to iterate the values?

user2941526
  • 497
  • 3
  • 6
  • 17

4 Answers4

2

Here is how you can do it with a very small modification to your code:

for (Map.Entry<Integer,Integer> entry : map1.entrySet()) {
    for (Integer value : map2.values()) {
        if (value.equals(entry.getKey())) {
            entry.setValue(entry.getValue()+1);
        }
    }
}

EDIT : Since map2 could contain the same value more than once, the other solution that uses a hash set to speed things up will not work as expected.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • Thanks for the help! with this set up I am getting just 1 for the values of map1. I need plus 1 for each time a map1 key equals a map2 value. Do I just need to move the "+1" elsewhere? – user2941526 Dec 20 '13 at 18:28
  • @user2941526 I see - `map2` can have the same value multiple times, right? Then you should the version with two loops. – Sergey Kalinichenko Dec 20 '13 at 18:31
  • You should probably use `.equals`, not `==`, since you're working with boxed `Integer` objects. – Louis Wasserman Dec 20 '13 at 22:00
  • @LouisWasserman Absolutely! Thank you very much - I copy/pasted the code, and missed this important issue. Great spotting! Thanks! – Sergey Kalinichenko Dec 20 '13 at 22:02
0

I'm not sure why Eclipse report a syntax error, but in any case this loop does not make much sense, consider changing it to:

for (Integer value : map2.values())
    if (map1.containsKey(value))
        // bla bla

it will run in O(n) rather than the former O(n*m)

when n is the size of map2 and m is the size of map1 (as notified by @dasblinkenlight)

Guy Gavriely
  • 11,228
  • 6
  • 27
  • 42
0

How you init yours maps? Like Map<Integer, Integer> map1=new LinkedHashMap<Integer, Integer>(); or Map map1=new LinkedHashMap(); If the second way the key will be Object not Integer. And in all cases compare two Integer using == bad practise. Use equals

Fireworks
  • 505
  • 2
  • 11
0

You can use containsKey method like this:

for (Integer value : map2.values()){
if (map1.containsKey(value))
    map1.put(key, value);

...
}
Chaitanya
  • 336
  • 2
  • 5
  • 13