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

问题描述 投票:2回答:4

我有两个哈希图:

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中检索唯一键值对。但这并没有给我mapA的所有键的详细信息。我明白这种方式存在缺陷,但我无法提出正确的逻辑。谁能让我知道如何将mapA和mapB中常见的键值对检索到新的HashMap中?

java
4个回答
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()));

1
投票

尝试以下逻辑:

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

0
投票

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

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

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

但是,您也可以在没有TreeSet的情况下创建HashMap,如@Ramesh和@NiVeR所示


0
投票

使用Guava Util Sets

Set<String> intersectionSet = Sets.intersection(firstSet, secondSet);
© www.soinside.com 2019 - 2024. All rights reserved.