有没有办法搜索并获取两个HashMap
对象中包含的密钥子集?Java:检查密钥是否包含在两个HashMap中
到现在为止,我总是从一个hashmap进行迭代,并在第二个寻找匹配。
我只是想知道是否有更聪明的方法来做这个比较。
有没有办法搜索并获取两个HashMap
对象中包含的密钥子集?Java:检查密钥是否包含在两个HashMap中
到现在为止,我总是从一个hashmap进行迭代,并在第二个寻找匹配。
我只是想知道是否有更聪明的方法来做这个比较。
如何
List<String> listOne = new ArrayList<String>(mapOne.keySet());
List<String> listTwo = new ArrayList<String>(mapTwo.keySet());
List<String> listThree = new ArrayList<String>(listTwo);
listThree.retainAll(listOne);
CollectionUtils.intersection(java.util.Collection a, java.util.Collection b)
在小于O(N)的复杂度下没有办法做到这一点。你唯一能做的就是迭代最小的散列表。 你可以做的另一件事是使用hashmaps的键集并使用方法retainAll
,它为你执行交集,但复杂性不会改变。
使用一个HashSet。如果你的用例需要有(key,value)对,那么同时维护一个HashMap和一个HashSet,并且每当在HashMap中插入一个密钥时,也将它插入到HashSet中。否则,只需维护一个HashSet。
然后,您可以使用retainAll()函数来查找两个集合的交集。
HashSet intersection = hashSet1.retainAll(hashSet2);
时间复杂度为O(n)摊销。这与你正在做的事情几乎一样,但是这会让你的代码更加干净和可读。
请注意,您可以维护List而不是Set,并调用list的retainAll()方法。然而,List的retainAll()将以O(n^2)复杂度运行,因为List的contains()方法在O(n)中运行,而HashSet的contains()在O(1)中运行。
您可以通过删除使用removeAll
所有键创建newMap
与inlin意见如下:
Map<String, String> map1 = new HashMap<>();
Map<String, String> map2 = new HashMap<>();
Set<Entry<String, String>> set1 = map1.entrySet();//get the entries from Map1
set1.removeAll(map2.entrySet());/remove all matched entries mateched in map2
Map<String, String> newMap = set1.stream().//convert set1 to Map using stream
collect(Collectors.toMap(Entry::getKey, Entry::getValue));
本例使用Map<String, String>
,但对自定义类可以适用于任何类型的(当然,你需要以覆盖来自java.lang.Object
的equals()
和hashcode()
方法)。
可能不是最有效的方式做到这一点,但这个Java 8的一行工作
Map<Integer,Integer> mapA = ..... // your first map
Map<Integer,Integer> mapB = ..... // your second map
List<Integer> keys = mapA.entrySet().stream().filter((v) -> mapB.containsKey(v.getKey()))
.map(v -> v.getKey()).collect(Collectors.toList());