Java 检查一个映射是否包含另一个映射的所有内容
我正在尝试检查一个地图是否包含另一个地图的所有内容。例如,我有一个Java 检查一个映射是否包含另一个映射的所有内容,java,hashmap,contains,Java,Hashmap,Contains,我正在尝试检查一个地图是否包含另一个地图的所有内容。例如,我有一个mapA,它是一个Map,元素是: "1" -> ["a","b"] "2" -> ["c","d"] "1" -> ["a"] "2" -> ["c","d"], 另一个mapB,也是Map,元素包括: "1" -> ["a","b"] "2" -> ["c","d"] "1" -> ["a"] "2" -> ["c","d"], 我想创建一个函数compare(mapA,
mapA
,它是一个Map
,元素是:
"1" -> ["a","b"]
"2" -> ["c","d"]
"1" -> ["a"]
"2" -> ["c","d"],
另一个mapB
,也是Map
,元素包括:
"1" -> ["a","b"]
"2" -> ["c","d"]
"1" -> ["a"]
"2" -> ["c","d"],
我想创建一个函数compare(mapA,mapB)
,在这种情况下它将返回false
最好的方法是什么?在比较(mapA,mapB)
方法中,您可以简单地使用:
return mapA.entrySet().containsAll(mapB.entrySet());
@jacobg提供的答案在您的案例中不起作用。只有在
MapA
中有一个额外的(键、值)对时,它才会工作。像
MapA = {"1" -> ["a","b"] "2" -> ["c","d"] }
及
您需要的是:
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);
}
布尔ISTrictlyDomain(LinkedHashMap firstMap,LinkedHashMap secondMap){
对于(Map.Entry项:secondMap.entrySet()){
int secondMapKey=item.getKey();
if(firstMap.containsKey(secondMapKey)){
HashSet secondMapValue=item.getValue();
HashSet firstMapValue=firstMap.get(secondMapKey);
如果(!firstMapValue.containsAll(secondMapValue)){
返回false;
}
}
}
return!firstMap.equals(secondMap);
}
(如果不想检查严格控制,那么最后只需return
truereturn
语句)尝试以下代码:
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());
}
在本例中,我编写的compare(mapA,mapB)
方法将返回true
比较(mapA,mapB)
方法基本上检查mapA和mapB中的所有条目,如果相同,则返回yes,否则返回false 为了你未来的理智,不要称之为比较。你不是在比较。将其称为containsAll
或subsumes
。但这也会检查值吗?如果没有,有什么更好的方法来检查键和值?@theprogrammer我不知道为什么我从来没有回复过你的评论,但是是的,这将检查mapB
中mapA
中是否存在所有条目。一个条目由一个键和一个值组成,条目相等由键相等和值相等决定。
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));