-2

I have two linkedHashmaps which are the same length with the same key names but the values are different. for example :

Map<String, Double> map1= new LinkedHashMap<String, Double>(); 

map1.put("A", 2.3);    
map1.put("B", 6.1);
map1.put("C", 5.3);

Map<String, Double> map2= new LinkedHashMap<String, Double>(); 

map2.put("A", 10.3);    
map2.put("B", 60.1);
map2.put("C", 0.3);

How would I multiply each value from map1 with the same corresponding key in map2 (A 2.3*10.3, B 6.1*60.1 etc etc) and save the results to a new linkedHashMap?

I tried this with no luck.

Map<String, Double> map3= new LinkedHashMap<String, Double>();
                double valueMap1 = map1.get(key);
                double valueMap2 = map2.get(key1);

            for(String key : map1.keySet())
                for(String key1 : map2.keySet()){
            if(map1.containsKey(key1)){


                double newValue =valueMap1* valueMap2;


                map3.put(key1, newValue);
        }
      }
  • With bare hand, what did you try? –  Aug 08 '16 at 16:39
  • The solution is very simple, please explain what have you tried and where did you fail. If you haven't tried anything first then go try and if it didn't work then ask – Michael Gantman Aug 08 '16 at 16:51
  • Is the order of keys in your two linkedhashmaps the same? Then you can get values of sorted maps as list and make required multiplications, saving the values to new list, and then combine keys and values. – lenach87 Aug 08 '16 at 16:53
  • @MichaelGantman I have added what I tried to no success, I'm relatively new to maps so I feel pretty lost with this problem. – Newbie2015Giant Aug 08 '16 at 21:32
  • You should not use a nested loop. Only one loop for this task. – SedJ601 Aug 08 '16 at 21:56
  • If the keys are the same, simply use the outer for loop key. Also, I think you want to get rid of the if statement. – SedJ601 Aug 08 '16 at 21:59

1 Answers1

1

Here is the loop that should solve your problem

Map<String, Double> map3= new LinkedHashMap<String, Double>();
for(String key : map1.keySet()) {
    if(map2.containsKey(key)) {
       map3.put(key, map1.get(key) * map2.get(key);
    }
}
Michael Gantman
  • 7,315
  • 2
  • 19
  • 36