2017-04-11 126 views

回答

1

如何

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); 

或者 Commons Collections

CollectionUtils.intersection(java.util.Collection a, java.util.Collection b) 
0

在小於O(N)的複雜度下沒有辦法做到這一點。你唯一能做的就是迭代最小的散列表。 你可以做的另一件事是使用hashmaps的鍵集並使用方法retainAll,它爲你執行交集,但複雜性不會改變。

0

使用一個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)中運行。

0

您可以通過刪除使用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.Objectequals()hashcode()方法)。

0

可能不是最有效的方式做到這一點,但這個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());