How can I check if the map1 dictionary map1 all <Key, Value> pairs contained in map2 ?

  • Run through one map and check that there are such keys in the other one and the same values ​​correspond to these keys, and that's all. - Alex Chermenin
  • "All those data" - do you mean that all the keys from map1 must be contained in map2, or must map2 contain the same keys with the same values? - m. vokhm
  • @AlexChermenin and what method is there no thread that would do this? - NoName
  • @ m.vokhm same keys with the same values - NoName

1 answer 1

Depending on whether you need to check only the presence in map1 all the keys from map2 , or also the equality of the corresponding values, you can use one of two methods:

 static boolean containsAllEntries(Map<?,?> map1, Map<?,?> map2) { return map1.entrySet().containsAll(map2.entrySet()); } static boolean containsAllKeys(Map<?,?> map1, Map<?,?> map2) { return map1.keySet().containsAll(map2.keySet()); } public static void main(String[] args) { HashMap<String, String> map1 = new HashMap<>(), map2 = new HashMap<>(); map1.put("1", "Один"); map2.put("1", "Один"); map1.put("2", "Два"); map2.put("2", "Два"); map1.put("3", "Три"); map1.put("3", "Три"); map1.put("4", "Четыре"); map1.put("5", "Пять"); System.out.println("map1 contains all keys from map2: " + containsAllKeys(map1, map2)); System.out.println("map1 contains all entries from map2: " + containsAllEntries(map1, map2)); map1.put("2", "Не два!"); System.out.println("map1 contains all keys from map2: " + containsAllKeys(map1, map2)); System.out.println("map1 contains all entries from map2: " + containsAllEntries(map1, map2)); map1.remove("2"); System.out.println("map1 contains all keys from map2: " + containsAllKeys(map1, map2)); System.out.println("map1 contains all entries from map2: " + containsAllEntries(map1, map2)); }