问题:
I have two maps and I need to check if both has the same keys and same number of keys or not and return a boolean. I would like to use streams for this and I have got is by...
可以将文章内容翻译成中文,广告屏蔽插件会导致该功能失效:
问题:
I have two maps and I need to check if both has the same keys and same number of keys or not and return a boolean. I would like to use streams for this and I have got is by creating another list
mapA
.entrySet()
.stream()
.filter(entry -> mapB.containsKey(entry.getKey()))
.collect(
Collectors.toMap(Entry::getKey, Entry::getValue));
But my question is that can I do it in a single line that would not create another list but return a boolean whether if they are same or not.
回答1:
There's no need to use streams for this. Just obtain the maps' key sets and use equals
, which is specified in Set
as follows:
Returns true
if the specified object is also a set, the two sets have the same size, and every member of the specified set is contained in this set [.]
Map<String, Integer> m1 = new HashMap<>();
m1.put("a", 10);
m1.put("b", 10);
m1.put("c", 10);
Map<String, Integer> m2 = new HashMap<>();
m2.put("c", 20);
m2.put("b", 20);
m2.put("a", 20);
System.out.println(m1.keySet().equals(m2.keySet())); //true
回答2:
You need to check if they are the same, so you can use:
boolean check = mapA.size() == mapB.size() && mapA.keySet().containsAll(mapB.keySet());
This means, that every entry from mapB
is in mapA
and their sizes are equal, so they contain same elements. @Holger suggests checking size first for better performance.