Reputation: 201
I am trying to check whether a map contains all contents of another map. For example, I have a mapA
which is a Map<String, List<String>>
and the elements are:
"1" -> ["a","b"]
"2" -> ["c","d"]
another mapB
which is also a Map<String, List<String>>
, the elements are:
"1" -> ["a"]
"2" -> ["c","d"],
I want to create a function compare(mapA, mapB)
which will return false in this case.
What is the best way to do this?
Upvotes: 20
Views: 23421
Reputation: 680
you can try this.
static boolean compare(Map<String, List<String>> mapA, Map<String, List<String>> mapB){
return mapA.entrySet().containsAll(mapB.entrySet());
}
As suppose, provided data is something like this:
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));
In this case compare(mapA, mapB)
method will return false.
But suppose provided data is something like this:
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));
In this case, compare(mapA, mapB)
method, which I have written will return true.
compare(mapA, mapB)
method basically checking for all the entries in mapA with mapB, if same returning yes, else returning false;
Upvotes: 0
Reputation: 513
Try this code :
Assert.assertTrue(currentMap.entrySet().containsAll(expectedMap.entrySet()));
Upvotes: 1
Reputation: 25
The answer provided by @Jacob G wont work in your case. It will work only if there is an extra (key, value) pair in MapA
. like
MapA = {"1" -> ["a","b"] "2" -> ["c","d"] }
and
MapB = {"1" -> ["a","b"] }.
What you need is this:
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);
}
(if you do not want to check strict domination then just return
true at last return
statement)
Upvotes: 0
Reputation: 29700
Inside your compare(mapA, mapB)
method, you can simply use:
return mapA.entrySet().containsAll(mapB.entrySet());
Upvotes: 28