Compare two maps for keys and return boolean

问题: 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.

  • 发表于 2019-03-27 05:13
  • 阅读 ( 172 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除