一个List中包含多个Map对象,根据多个对象中相同key进行求和,放到一个新的Map里
时间: 2024-04-07 09:30:08 浏览: 27
可以通过遍历List中的Map对象,然后根据相同的key进行求和,并将结果放到一个新的Map中。以下是一个示例代码:
```java
import java.util.*;
public class MapSummation {
public static void main(String[] args) {
List<Map<String, Integer>> mapList = new ArrayList<>();
Map<String, Integer> resultMap = new HashMap<>();
// 假设有三个Map对象
Map<String, Integer> map1 = new HashMap<>();
map1.put("key1", 10);
map1.put("key2", 20);
map1.put("key3", 30);
Map<String, Integer> map2 = new HashMap<>();
map2.put("key1", 15);
map2.put("key2", 25);
map2.put("key4", 35);
Map<String, Integer> map3 = new HashMap<>();
map3.put("key1", 5);
map3.put("key3", 15);
map3.put("key5", 25);
// 将三个Map对象加入List
mapList.add(map1);
mapList.add(map2);
mapList.add(map3);
// 遍历List中的Map对象
for (Map<String, Integer> map : mapList) {
// 遍历当前Map的键值对
for (Map.Entry<String, Integer> entry : map.entrySet()) {
String key = entry.getKey();
int value = entry.getValue();
// 如果新的Map中已经有该键,则将当前值与新值相加
if (resultMap.containsKey(key)) {
int sum = resultMap.get(key) + value;
resultMap.put(key, sum);
} else {
// 如果新的Map中没有该键,则直接放入新的键值对
resultMap.put(key, value);
}
}
}
// 打印结果
for (Map.Entry<String, Integer> entry : resultMap.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
}
}
```
以上代码中,我们使用一个List来存储多个Map对象,然后使用一个新的Map来存储求和的结果。通过遍历List中的Map对象,再遍历每个Map对象中的键值对,判断新的Map中是否已经存在相同的键,如果存在则将对应的值相加,如果不存在则直接放入新的键值对。最后打印出新的Map中的结果。
运行以上代码将得到以下输出:
```
key1: 30
key2: 45
key3: 45
key4: 35
key5: 25
```
可以看到,根据相同的key进行了求和,并放入了新的Map中。