java代码举例两个map取交集
时间: 2024-01-24 18:05:01 浏览: 70
好的,以下是 Java 代码举例两个 Map 取交集:
```
Map<String, Integer> map1 = new HashMap<>();
map1.put("a", 1);
map1.put("b", 2);
map1.put("c", 3);
Map<String, Integer> map2 = new HashMap<>();
map2.put("b", 4);
map2.put("c", 5);
map2.put("d", 6);
Map<String, Integer> intersection = new HashMap<>(map1);
intersection.keySet().retainAll(map2.keySet());
System.out.println("Map1: " + map1);
System.out.println("Map2: " + map2);
System.out.println("Intersection: " + intersection);
```
运行结果为:
```
Map1: {a=1, b=2, c=3}
Map2: {b=4, c=5, d=6}
Intersection: {b=2, c=3}
```
希望这个例子对你有帮助!
阅读全文