0

I have two maps:

Map1.put(a,1)
Map1.put(b,2)
Map1.put(c,3)
Map1.put(d,4)

Map2.put(a,1)
Map2.put(b,5)
Map2.put(c,3)
Map2.put(d,4)
Map2.put(e,6)
Map2.put(f,9)

How do I compare Map1 and Map2 for equal key values? If the key is not matching in Map2 then ignore that key.

Scott Newson
  • 2,745
  • 2
  • 24
  • 26
  • Extract the key sets from each map and use the methods outlined in https://stackoverflow.com/q/3341202/13075. – Henrik Aasted Sørensen Aug 16 '17 at 14:06
  • Possible duplicate of [What is the fastest way to compare two sets in Java?](https://stackoverflow.com/questions/3341202/what-is-the-fastest-way-to-compare-two-sets-in-java) – Ori Marko Aug 16 '17 at 14:10

3 Answers3

3

get the keySet() of every map and use the ContainsAll() method

Map<String, Integer> Map1 = new HashMap<>();
Map1.put("a", 1);
Map1.put("b", 2);
Map1.put("c", 3);
Map1.put("d", 4);

Map<String, Integer> Map2 = new HashMap<>();
Map2.put("a", 1);
Map2.put("b", 5);
Map2.put("c", 3);
Map2.put("d", 4);
Map2.put("e", 6);
Map2.put("f", 9);

// check if all keys from Map1 are present in Map2
System.out.println(Map2.keySet().containsAll(Map1.keySet()));
AmrDeveloper
  • 3,826
  • 1
  • 21
  • 30
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
1

Try intersection() with Entries. It will check keys and values and return common entries.

Map<String, Integer> map1 = new HashMap<>();
map1.put("a", 1);
map1.put("b", 2);
map1.put("c", 3);
map1.put("d", 4);

Map<String, Integer> map2 = new HashMap<>();
map2.put("a", 2);
map2.put("b", 3);
map2.put("c", 4);
map2.put("d", 5);
map2.put("e", 6);
map2.put("f", 9);

Collection<Map.Entry<String, Integer>> commonValues = CollectionUtils.intersection(map1.entrySet(), map2.entrySet());

System.out.println(CollectionUtils.isEmpty(commonValues)); // if empty, then no same key and value found.

For keys alone use :

Collection<String> commonKeys = CollectionUtils.intersection(map1.keySet(), map2.keySet()); 
Neuron
  • 5,141
  • 5
  • 38
  • 59
John Tribe
  • 1,407
  • 14
  • 26
0

This is another simple solution.

Map1.keySet().retainAll(Map2.keySet());

Map1.keySet() contains only keys in both sets

nagendra547
  • 5,672
  • 3
  • 29
  • 43