【发布时间】: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())[