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 k开发者_JAVA百科eys in the 2 maps.
How can i do that?
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.
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);
Map comparisons are made easier by Maps.difference(..) method from Google's guava libraries.
boolean hasOverlap = m1.keySet().retainAll(m2.keySet());
精彩评论