Comparing Maps by keySet
equals, java, maps
Solution
Maps can have same keys but different values:
Map<String, String> m1 = new HashMap<>();
m1.put("x", "1");
m1.put("y", "2");
Map<String, String> m2 = new HashMap<>();
m2.put("x", "1");
m2.put("y", "4");
System.out.println(m1.equals(m2)); // false
System.out.println(m1.keySet().equals(m2.keySet())); // true
Problem
In the this oracle java it says that: Along similar lines, suppose you want to know whether two Map objects contain mappings for all of the same keys. if (m1.keySet().equals(m2.keySet())) { ... } I thoroughly understand that it works and also how it works. However would not be easier doing something like : ``` if (m1.equals(m2)){ ..} ``` Or for other reasons that I am not seeing it's better using the collection view? Thanks in advance.