代码之家  ›  专栏  ›  技术社区  ›  Metadata

如何从两个哈希映射中检索公共键值对

  •  2
  • Metadata  · 技术社区  · 7 年前

    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");
    

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

    然后使用 treeset: uniquekeys 有人能告诉我如何将mapa和mapb中常见的键值对检索到新的hashmap中吗?

    4 回复  |  直到 6 年前
        1
  •  1
  •   Samuel Philipp    6 年前

    您可以用Java 8流来执行以下操作:

    Map<String, String> commonMap = mapA.entrySet().stream()
            .filter(x -> mapB.containsKey(x.getKey()))
            .collect(Collectors.toMap(x -> x.getKey(), x -> x.getValue()));
    
        2
  •  1
  •   Ramesh    7 年前

    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));
                    }
                }
            }
    
        3
  •  0
  •   Kepotx    7 年前

    您可以用公共值填充树集,而不是向树集添加所有键:

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

    但是,正如@ramesh和@niver建议的那样,您也可以在不使用treeset的情况下创建哈希图。

        4
  •  0
  •   linuxlsx    7 年前

    Set<String> intersectionSet = Sets.intersection(firstSet, secondSet);