If I have two HashMaps, hm1 and hm2, how can I iterate through the two and multiply the two values together at each point in the two HashMaps and sum the total? They are both ordered identically, so I don’t need to worry about the keys, just the values.
The data is in the form
hm1 = (A, 3) (B, 4) (C, 7) hm2 = (A, 4) (B, 6) (C, 3)
then I want to do something like this but obviously this code is incorrect because I’m only iterating through hm1.
double sum = 0.00;
for (Map.Entry<String, Double> hm : hm1.entrySet()) {
sum += hm1.getValue() * hm2.getValue();
}
So I would basically loop through and do:
1st iteration: Sum = 0 + 3*4 2nd Iteration: Sum = 12 + 4*6 3rd iteration: Sum = 36 + 7*3 Exit Loop: Sum = 57
Thanks for any help you can give me.
Advertisement
Answer
You can use the key from your iteration over the first map to get the value for the second one:
double sum = 0.00;
for (Map.Entry<String, Double> hm : hm1.entrySet()) {
double hm2Value = hm2.get(hm.getKey());
sum += hm.getValue() * hm2Value;
}
Note that this only works if both maps have the same keys. If keys are missing in either, then you have to think about how to deal with that.