java代码实现比较两个map取出相同值
时间: 2023-06-18 21:06:59 浏览: 60
可以通过以下代码实现比较两个 Map 取出相同值:
```java
import java.util.*;
public class MapComparison {
public static void main(String[] args) {
Map<Integer, String> map1 = new HashMap<>();
map1.put(1, "One");
map1.put(2, "Two");
map1.put(3, "Three");
Map<Integer, String> map2 = new HashMap<>();
map2.put(3, "Three");
map2.put(4, "Four");
map2.put(5, "Five");
// Create a new map to store the common values
Map<Integer, String> commonValues = new HashMap<>();
// Iterate through the first map and check if the value exists in the second map
for (Map.Entry<Integer, String> entry : map1.entrySet()) {
if (map2.containsValue(entry.getValue())) {
commonValues.put(entry.getKey(), entry.getValue());
}
}
// Print the common values
System.out.println("Common values: " + commonValues);
}
}
```
输出结果为:
```
Common values: {3=Three}
```