简体   繁体   English

比较不同哈希表的键

[英]compare keys of different Hashmaps

Let's say I have 2 Map's in Java. 假设我在Java中有2个Map。 I want to compare map1's keys to map2's keys to see if there are any similar keys in the 2 maps. 我想将map1的键与map2的键进行比较,以查看2张地图中是否有相似的键。

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. 如果您的键是日期,则它们可能应该是Comparable ,在这种情况下,您可能需要TreeSet而不是HashSet,因为它将使它们保持顺序。

Something like that ? 这样的事? If you want don't remove from m1 then you can do this m3 = new(m1) 如果您不想从m1中删除,则可以执行以下操作: 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 libraries. Google的库中的Maps.difference(..)方法使地图比较变得更加容易。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM