在两个地图中乘以相应值的最佳方法

Best way to multiply corresponding values in two maps

如何将 map1 的值乘以它在 map2 中的对应值?我已经尝试了两个 for 循环,但它遍历了两个地图 16 次。假设两个地图的长度始终相同。

Map<String, Integer> map1= new HashMap<>();
Map<String, Integer> map2= new HashMap<>();

map1.put("one", 1);
map1.put("two", 2);
map1.put("three", 3);
map1.put("four", 4);

map2.put("one", 1);
map2.put("two", 2);
map2.put("three", 3);
map2.put("four", 4);

//map1 = {(one, 1), (two, 2)... etc
//map2 = the same

for(Integer num:map1.values()){
    for(Integer num2:map1.values()){
        total = num * num2;}}
System.out.println(total);

我做错了什么。我想将每个值相乘并得到总和,即 (1 * 1) + (2 * 2)...

java 地图中的

Key/value 对是无序的。无法保证当您遍历以下值时,您将获得相同顺序的值。

for(Integer num:map1.values())[
    for(Integer num2:map1.values()){
        total = num * num2;}}
System.out.println(total);

下面会做

for (Map.Entry<String, Integer> entry : map1.entrySet()) {
    String key = entry.getKey();
    int value = entry.getValue();
    total += value * map2.get(key);
}
System.out.println(total);

以上代码假设您始终拥有 map2map1 的密钥!其复杂度为 O(n)* O(1),其中 n 为 map1 中的键数。访问 map2 中的值被认为是常量。

流式传输条目,将每个条目的值乘以其在另一个映射中的匹配值,然后求和:

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

您应该迭代一个地图的键,从另一个地图获取相关值(可能使用 getOrDefault 到 return 缺失键的默认值)并计算它们的总和产品:

int total = 0;

for (String key : map1.keySet()) {
    total += map1.get(key) * map2.getOrDefault(key, 0);
}

使用流的类似解决方案API:

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