java - 如何从两个 HashMap 中检索公共(public)键值对

标签 java

我有两个 HashMap :

Map<String, String> mapA = new HashMap<String, String>();
Map<String, String> mapB = new HashMap<String, String>();
TreeSet<String> uniquekeys = new TreeSet<String>();
mapA.put("1","value1");
mapA.put("2","value2");
mapA.put("3","value3");
mapA.put("4","value4");
mapA.put("5","value5");
mapA.put("6","value6");
mapA.put("7","value7");
mapA.put("8","value8");
mapA.put("9","value9");
mapB.put("1","value1");
mapB.put("2","value2");
mapB.put("3","value3");
mapB.put("4","value4");
mapB.put("5","value5");

为了从两个 HashMap 中获取公共(public)键值对,我编写了以下逻辑:

uniquekeys.addAll(mapA.keySet());
uniquekeys.addAll(mapB.keySet());

然后使用treeset: uniquekeys中的键从mapA和mapB中检索唯一的键值对。 但这并没有给我来自mapA的所有键的详细信息。我知道这种方式有缺陷,但我无法想出正确的逻辑。 谁能告诉我如何将mapA和mapB中常见的键值对检索到新的HashMap中?

最佳答案

尝试以下逻辑:

Map<String, String> common = new HashMap<String, String>();
        for(String key : mapA.keySet()) {
            if(mapB.get(key) !=null ) {
                if(mapA.get(key).equals(mapB.get(key))) {
                    common.put(key, mapA.get(key));
                }
            }
        }

关于java - 如何从两个 HashMap 中检索公共(public)键值对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51039668/

相关文章:

java - 如果特定场景出现在 webdriver 中,如何运行它

java - 具有静态最终限制的数组迭代

JavaFX:初始化单选按钮选择状态

java - 如何设置从 soapui 获取带有 json 正文的请求?

java - 如何在 Java 中处理多个退出点

java - 批处理文件不会运行 Java Main 类

java - 如何使 Jersey @RolesAllowed 与 @Stateless 一起工作?

java - 我的树形图在排序后中断,因为 "comparator used for the treemap is inconsistent with equals"

java - 双属性上的比较器排序无法满足其一般契约

java - 如何在图像周围环绕文字?