如何比较两个Map并返回有效的键值对Map

bihw5rsg  于 2021-07-24  发布在  Java
关注(0)|答案(1)|浏览(277)
Map<String, String> hash_map = new LinkedHashMap<String, String>(); 

    Map<String, String> new_hash_map = new LinkedHashMap<String, String>();

    hash_map.put("AA", "Geeks"); 
    hash_map.put("BB", "4"); 
    hash_map.put("CC", "Geeks"); 
    hash_map.put("DD", "Welcomes"); 
    hash_map.put("EE", "You"); 

    new_hash_map.put("BB", "4");
    new_hash_map.put("EE", "You");
    new_hash_map.put("FF", "Me");

哈希Map包含一些键和值,新的哈希Map还包含一些键和值。我的要求是将新的散列Map与散列Map进行比较,并返回新散列Map的有效键值对Map

edqdpe6u

edqdpe6u1#

您可以使用stream with java 8以这种方式获取Map之间的交集:

Map<String, String> intersection = hash_map.entrySet().stream()
                .filter(map -> (new_hash_map.containsKey(map.getKey())
                        && new_hash_map.get(map.getKey()).equals(map.getValue())))
                .collect(Collectors.toMap(map -> map.getKey(), map -> map.getValue()));

这段代码使用过滤器将值Map到 key 以及 value 都是一样的。i、 两张Map的交集。
和价值 intersection 变量为: {EE=You, BB=4} .
我还补充了 new_hash_map.put("CC", "Me"); 确保 CC 未输出密钥。

相关问题