简体   繁体   English

比较两个 HashMap 并乘以 map 值

[英]Compare two HashMap and multiply map values

I have two HashMap and lets say they having the following values:我有两个 HashMap 并且可以说它们具有以下值:

 HashMap1 : <x, 1>, <y, 2>, <z, 3>

 HashMap2 : <x,10>, <y, 20>, <z,30>

I want to multiply corresponding values then sum these values like: 1*10 + 2*20 + 3*30.我想将相应的值相乘,然后将这些值相加,例如:1*10 + 2*20 + 3*30。 However, I am not sure if I have to use 2 loops or some other iteration.但是,我不确定是否必须使用 2 个循环或其他一些迭代。 I use one loop but it did no solved the problem:我使用一个循环,但它没有解决问题:

for (Map.Entry<Character, Integer> entry : map1.entrySet()) {
    int sum=0;
    if(map2.containsKey(entry.getKey())) {
        sum+=entry.getValue() * ...; //it gets map1 values but I also need map2 values to multiply
    }
}

How to fix it?如何解决?

Before Java 8 : Java 8之前:

int sum = 0;
for (Map.Entry<String, Integer> entry : map1.entrySet()) {
    sum += entry.getValue() * map2.getOrDefault(entry.getKey(), 1);
}

Since Java 8 :Java 8起:

int sum = map1.entrySet().stream()
   .mapToInt(e -> e.getValue() * map2.getOrDefault(e.getKey(), 1)).sum();

Note:笔记:
You need to also handle keys which are different between two maps.您还需要处理两个地图之间不同的键。 I assumed that these two maps contains exactly the same keys.我假设这两个映射包含完全相同的键。 Just to keep it simple and clear.只是为了保持简单明了。

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

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