Chamal
Chamal

Reputation: 1127

compare keys of different Hashmaps

Let's say I have 2 Map's in Java. I want to compare map1's keys to map2's keys to see if there are any similar keys in the 2 maps.

How can i do that?

Upvotes: 0

Views: 4060

Answers (4)

Andrejs
Andrejs

Reputation: 27677

Map comparisons are made easier by Maps.difference(..) method from Google's libraries.

Upvotes: 1

Tom Anderson
Tom Anderson

Reputation: 47183

If you don't want to modify the maps:

boolean thereAreCommonKeys = !Collections.disjoint(one.keySet(), two.keySet());

Finding the common keys:

Set<K> commonKeys = new HashSet<K>(one.keySet());
commonKeys.retainAll(two.keySet());

If your keys are dates, they should probably be something Comparable, in which case you might want a TreeSet instead of a HashSet, because it will keep them in order.

Upvotes: 7

user467871
user467871

Reputation:

Something like that ? If you want don't remove from m1 then you can do this m3 = new(m1)

Map<Integer, Integer> m1 = new HashMap<Integer, Integer>();
Map<Integer, Integer> m2 = new HashMap<Integer, Integer>();

m1.put(1, 2);
m1.put(2, 3);

m2.put(1, 3);
m2.put(3, 4);

Map<Integer, Integer> m3 = new HashMap<Integer, Integer>(m1);  


Set s1 = m1.keySet();
Set s2 = m2.keySet();

System.out.println(s1);
System.out.println(s2);
System.out.println(s1.retainAll(s2));
System.out.println(s1);
System.out.println(s2);
System.out.println(m1);
System.out.println(m3);

Upvotes: 1

Robokop
Robokop

Reputation: 926

boolean hasOverlap = m1.keySet().retainAll(m2.keySet());

Upvotes: 0

Related Questions