【问题标题】:Best way to multiply corresponding values in two maps在两个地图中乘以对应值的最佳方法
【发布时间】:2021-11-13 21:47:29
【问题描述】:

如何将 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)...

【问题讨论】:

  • 你知道哪些key需要提前复数吗?
  • @AntonBelev 这将是地图中的每个键
  • for(Integer num:map1.values())[

标签: java loops hashmap sum


【解决方案1】:

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

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

【讨论】:

  • @AlexRudenko 谢谢。固定。
【解决方案2】:

java 映射中的键/值对是无序的。无法保证当您遍历下面的值时,您将获得相同顺序的值。

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);

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

【讨论】:

  • 你建议的代码做同样的事情。当我正在寻找 30 的答案时,结果是 9。
  • 啊这是因为你需要增加总数。所以是+=
【解决方案3】:

您应该迭代一个映射的键,从另一个映射获取相关值(可能使用getOrDefault 为丢失的 ket 返回一个默认值)并计算它们的产品总数:

int total = 0;

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

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

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

【讨论】:

    猜你喜欢
    • 2011-10-27
    • 2019-03-28
    • 1970-01-01
    • 2012-11-20
    • 1970-01-01
    • 2010-11-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多