有沒有辦法搜索並獲取兩個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());