【问题标题】:How to retrieve common key value pairs from two hashmaps如何从两个哈希图中检索公共键值对
【发布时间】:2018-06-26 09:40:28
【问题描述】:

我有两个哈希图:

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 中获取公共键值对,我编写了以下逻辑:

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

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

【问题讨论】:

  • 新 Map 包含哪些公共键? mapA 的值还是 mapB 的值?还是应该只包含两个 Map 中具有相同键值的键值对?
  • 新地图应该包含在mapA和mapB中通用的键值对。
  • @Sidhartha 你试过retainAll吗?
  • 您介意使用外部库吗? Google Guava 提供了比较集合的工具:google.github.io/guava/releases/21.0/api/docs/com/google/common/…

标签: java


【解决方案1】:

您可以通过以下方式使用 Java 8 Streams:

Map<String, String> commonMap = mapA.entrySet().stream()
        .filter(x -> mapB.containsKey(x.getKey()))
        .collect(Collectors.toMap(x -> x.getKey(), x -> x.getValue()));

【讨论】:

    【解决方案2】:

    试试下面的逻辑:

    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】:

      您可以用公共值填充 TreeSet,而不是将所有键添加到 TreeSet:

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

      这样,A 中包含但 B 中不包含的键将被删除。知道你有你的 TreeSet,你可以做你想做的事。

      不过,您也可以按照 @Ramesh 和 @NiVeR 的建议在不使用 TreeSet 的情况下创建 HashMap

      【讨论】:

        【解决方案4】:

        使用 Guava 实用程序集

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2014-01-02
          • 1970-01-01
          • 1970-01-01
          • 2013-10-18
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多