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

Java 如何从两个哈希映射中检索公共键值对,java,Java,我有两个哈希映射: 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"

我有两个哈希映射:

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");
然后使用
树中的键set:uniquekeys
从mapA和mapB检索唯一的键值对。 但这并没有告诉我mapA所有钥匙的细节。我知道这种方式有缺陷,但我无法提出正确的逻辑。
有人能告诉我如何将mapA和mapB中常见的键值对检索到新的HashMap中吗?

您可以通过以下方式使用Java 8流执行此操作:

Map<String, String> commonMap = mapA.entrySet().stream()
        .filter(x -> mapB.containsKey(x.getKey()))
        .collect(Collectors.toMap(x -> x.getKey(), x -> x.getValue()));
Map commonMap=mapA.entrySet().stream()
.filter(x->mapB.containsKey(x.getKey()))
.collect(Collectors.toMap(x->x.getKey(),x->x.getValue());
尝试以下逻辑:

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));
                }
            }
        }
Map common=newhashmap();
for(字符串键:mapA.keySet()){
if(mapB.get(key)!=null){
if(mapA.get(key).equals(mapB.get(key))){
common.put(key,mapA.get(key));
}
}
}

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

uniquekeys.addAll(mapA.keySet());
uniquekeys.retainAll(mapB.keySet());
这样,将删除包含在A中但不包含在B中的密钥。知道你有你的树集,你可以做你想做的

但是,您也可以在不使用TreeSet的情况下创建HashMap,因为@Ramesh和@NiVeR建议使用Guava Util集合

Set<String> intersectionSet = Sets.intersection(firstSet, secondSet);
Set intersectionSet=Set.intersection(第一集,第二集);

新地图将包含哪些常用键?mapA的值还是mapB的值?或者它应该只包含在两个映射中具有相同键和值的键值对吗?新映射应该包含在mapA和mapB中都通用的键值对。@Sidhartha您尝试过保留吗?您介意使用外部库吗?Google Guava提供了比较集合的工具:
Set<String> intersectionSet = Sets.intersection(firstSet, secondSet);