Compare two maps for keys and return boolean

NewUser :

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.

rgettman :

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=307928&siteId=1