繁体   English   中英

检查一个地图是否包含另一个地图的所有内容

[英]Check whether a map contains all contents of another map

我正在尝试检查地图是否包含另一张地图的所有内容。 例如,我有一个mapA ,它是一个Map<String, List<String>>并且元素是:

"1" -> ["a","b"]
"2" -> ["c","d"]

另一个mapB也是一个Map<String, List<String>> ,元素是:

"1" -> ["a"]
"2" -> ["c","d"],

我想创建一个函数compare(mapA, mapB)在这种情况下将返回 false 。

做这个的最好方式是什么?

compare(mapA, mapB)方法中,您可以简单地使用:

return mapA.entrySet().containsAll(mapB.entrySet());

@Jacob G 提供的答案不适用于您的情况。 只有在MapA有额外的 (key, value) 对时,它才会起作用。 喜欢

MapA = {"1" -> ["a","b"] "2" -> ["c","d"] } 

MapB = {"1" -> ["a","b"]  }. 

你需要的是这个:

boolean isStrictlyDominate(LinkedHashMap<Integer, HashSet<Integer>> firstMap, LinkedHashMap<Integer, HashSet<Integer>> secondMap){
    for (Map.Entry<Integer, HashSet<Integer>> item : secondMap.entrySet()) {
        int secondMapKey = item.getKey();
        if(firstMap.containsKey(secondMapKey)) {
            HashSet<Integer> secondMapValue = item.getValue();
            HashSet<Integer> firstMapValue = firstMap.get(secondMapKey) ;
            if(!firstMapValue.containsAll(secondMapValue)) {
                return false;
            }

        }
    }
    return !firstMap.equals(secondMap);
}

(如果您不想检查严格控制,则只需在最后的return语句中return true)

试试这个代码:

Assert.assertTrue(currentMap.entrySet().containsAll(expectedMap.entrySet()));

你可以试试这个。

static boolean compare(Map<String, List<String>> mapA, Map<String, List<String>> mapB){
        return mapA.entrySet().containsAll(mapB.entrySet());
    }

假设,提供的数据是这样的:

            Map<String, List<String>> mapA = new HashMap<>();
            Map<String, List<String>> mapB = new HashMap<>();

            mapA.put("1", Arrays.asList("a","b"));
            mapA.put("2", Arrays.asList("c","d"));

            mapB.put("1", Arrays.asList("a"));
            mapB.put("2", Arrays.asList("c", "d"));

            System.out.println(compare(mapA, mapB));

在这种情况下, compare(mapA, mapB)方法将返回 false。 但假设提供的数据是这样的:

            Map<String, List<String>> mapA = new HashMap<>();
            Map<String, List<String>> mapB = new HashMap<>();

            mapA.put("1", Arrays.asList("a","b"));
            mapA.put("2", Arrays.asList("c","d"));

            mapB.put("1", Arrays.asList("a", "b"));
            mapB.put("2", Arrays.asList("c", "d"));

            System.out.println(compare(mapA, mapB));

在这种情况下,我编写的compare(mapA, mapB)方法将返回 true。

compare(mapA, mapB)方法基本上用mapB检查compare(mapA, mapB)中的所有条目,如果相同返回yes,否则返回false;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM