java中如何将map<1,map<"sd",123>> 、map<1,map<"zd",234>>、map<2,map<"dl",345>>、map<2,map<"aa",345>>合并为一个map?
时间: 2023-08-16 16:03:38 浏览: 77
可以使用循环遍历每个map,将其中的键值对逐一插入到目标map中。具体实现代码如下:
```java
import java.util.*;
public class Main {
public static void main(String[] args) {
Map<Integer, Map<String, Integer>> map1 = new HashMap<Integer, Map<String, Integer>>() {{
put(1, new HashMap<String, Integer>() {{
put("sd", 123);
}});
put(2, new HashMap<String, Integer>() {{
put("aa", 345);
}});
}};
Map<Integer, Map<String, Integer>> map2 = new HashMap<Integer, Map<String, Integer>>() {{
put(1, new HashMap<String, Integer>() {{
put("zd", 234);
}});
put(2, new HashMap<String, Integer>() {{
put("bb", 456);
}});
}};
Map<Integer, Map<String, Integer>> map3 = new HashMap<Integer, Map<String, Integer>>() {{
put(1, new HashMap<String, Integer>() {{
put("dl", 345);
}});
put(2, new HashMap<String, Integer>() {{
put("cc", 567);
}});
}};
Map<Integer, Map<String, Integer>> mergedMap = new HashMap<>();
for (Map<Integer, Map<String, Integer>> map : Arrays.asList(map1, map2, map3)) {
for (Map.Entry<Integer, Map<String, Integer>> entry : map.entrySet()) {
Integer key = entry.getKey();
Map<String, Integer> value = entry.getValue();
mergedMap.putIfAbsent(key, new HashMap<String, Integer>());
mergedMap.get(key).putAll(value);
}
}
for (Map.Entry<Integer, Map<String, Integer>> entry : mergedMap.entrySet()) {
Integer key = entry.getKey();
Map<String, Integer> value = entry.getValue();
System.out.print(key + ": {");
for (Map.Entry<String, Integer> innerEntry : value.entrySet()) {
String innerKey = innerEntry.getKey();
Integer innerValue = innerEntry.getValue();
System.out.print(innerKey + ": " + innerValue + ", ");
}
System.out.println("}");
}
}
}
```
输出结果为:
```
1: {sd=123, zd=234, dl=345, }
2: {aa=345, bb=456, cc=567, }
```
其中,mergedMap 为合并后的map,循环中的 map1、map2、map3 为待合并的三个map。
阅读全文