简体   繁体   English

将两个 HashMap 的值相乘

[英]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?如果我有两个HashMaphm1hm2 ,我如何遍历这两个并在两个HashMap的每个点将两个值相乘并求和? 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.然后我想做这样的事情,但显然这段代码是不正确的,因为我只是在遍历 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: 假设两个HashMap的条目数相等,并且所有条目具有相同的对应键,则获取总和的可靠方法如下所示:

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: Java 版本 8,您可以使用 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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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