简体   繁体   中英

Multiplying Values of Two HashMaps

If I have two HashMap s, hm1 and hm2 , how can I iterate through the two and multiply the two values together at each point in the two HashMap s 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.

Given that the two HashMaps have equal amount of entries, and that all the entries have the same corresponding key, then a solid way to aquire the sum would be like this:

double sum = 0;

/* iterate through all the keys in hm1 */
/* order doesn't matter */
for (String key : hm1.keySet()) {
    double value1 = hm1.get(key);
    double value2 = hm2.get(key);
    sum += value1 * value2;
}

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.

Java Version 8, you can use Stream API:

    Map<String, Double> hm1 = new HashMap<String, Double>() {{
        put("A", 3.0);
        put("B", 4.0);
        put("C", 7.0);
    }};

    Map<String, Double> hm2 = new HashMap<String, Double>() {{
        put("A", 4.0);
        put("B", 6.0);
        put("C", 3.0);
    }};

    double sum = hm1.entrySet()
        .stream()
        .filter(entry -> hm2.containsKey(entry.getKey()))
        .map(entry -> entry.getValue() * hm2.get(entry.getKey()))
        .mapToDouble(value -> value)
        .sum();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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