Java - 仅比较特定键的两个 Maps 条目

标签 java dictionary compare equals

假设我有两张 map :

    Map<String, String> map1 = Map.of(
        "a", "1",
        "b", "2",
        "c", "3",
        "x", "9"
    );
    Map<String, String> map2 = Map.of(
        "z", "9"
        "a", "1",
        "b", "2",
        "c", "3"
    );

现在我只想比较以下键的这些映射,看看它们是否包含相同的值:["a", "b", "c"]

一种直接的方法可以是:
public boolean customEquals(Map map1, Map map2){ //please ignore NullPointerException
    return map1.get("a").equals(map2.equals("a"))
            && map1.get("b").equals(map2.equals("b"))
            && map1.get("c").equals(map2.equals("c"));
}

但是,如果要检查更多的键,那么这对于编码来说非常低效且难闻。在这种情况下,更好的方法可以是:
public boolean customEquals(Map map1, Map map2) { //please ignore NullPointerException
    Set<String> keys = Set.of("a", "b", "c");
    for (String key : keys) {
        if (!(map1.get(key).equals(map2.get(key)))) {
            return false;
        }
    }
    return true;
}

有没有更好的方法来做到这一点? (你也可以推荐流行的库函数)

最佳答案

首先从 map1 获取 key=[a,b,c] 的条目或 map2进入 List

List<SimpleEntry<String,String>> res = Stream.of("a","b","c")
                                   .map(key->new AbstractMap.SimpleEntry<String,String>(key, map1.get(key)))
                                   .collect(Collectors.toList());   

然后你可以检查所有这些条目是否存在于另一个 Map 中。 ,这样你就不用担心 NullPointerException甚至任何 Map[a,b,c] 没有值(value)
res.stream().allMatch(entry->map2.entrySet().contains(entry))  //convert map2 to entrySet before using in allMatch

我们也可以将它们合并为一行
Stream.of("a","b","c")
         .map(key->new AbstractMap.SimpleEntry<String,String>(key, map1.get(key)))
         .allMatch(entry->map2.entrySet().contains(entry));

关于Java - 仅比较特定键的两个 Maps 条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59495969/

相关文章:

java - org.springframework.beans.factory.UnsatisfiedDependencyException : Error creating bean with name (controller)

java - 使用 Java 运行 PL/SQL block

java - 无法使用 webdriver 将文件上传到 Box.com

具有优先级的字符串中的Python搜索字典键

python - 获取嵌套字典与列表的组合数

mysql - SQL查询查找在某些2个日期增值的所有产品

java - 如何比较字符串组

java - 在不滚动到顶部的情况下更新 recyclerView 适配器

python - 递归访问嵌套字典的路径和值

c++ - 重载 < 运算符 C++