0

Is there a way to search and get a subset of keys that are contained in two HashMap objects?

Until now I have always made an iteration from a hashmap and looking for matches in the second.

I just wanted to know if there was a smarter way to do this comparison.

5 Answers 5

1

How about

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

Or Commons Collections

CollectionUtils.intersection(java.util.Collection a, java.util.Collection b) 
Sign up to request clarification or add additional context in comments.

Comments

0

There is no way to do that in a complexity less than O(N). The only thing you can do, is to iterate the smallest hashmap. Another thing you could do is to use the key sets of the hashmaps and use the method retainAll, which perform the intersection for you, but the complexity doesn't change.

Comments

0

Use a HashSet. If your use case needs to have (key, value) pairs, then maintain a HashMap and a HashSet both, and whenever a key is inserted in the HashMap, insert it in the HashSet as well. Otherwise, just maintain a HashSet.

Then you can use retainAll() function to find the intersection of the two sets.

HashSet intersection = hashSet1.retainAll(hashSet2); 

The time complexity will be O(n) amortised. This is almost the same as that of what you are doing, but this would make your code much cleaner and readable.

Note that you can maintain a List instead of Set and call the retainAll() method of list. However, retainAll() of List will run in O(n^2) complexity, because the contains() method of List runs in O(n) whereas contains() of HashSet runs in O(1) amortised.

Comments

0

You can create the newMap by removing all keys using removeAll as shown below with inlin comments:

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

This example uses Map<String, String>, but can be applied to any types (of course for custom classes, you need to override equals() and hashcode() methods from java.lang.Object).

Comments

0

Probably not the most efficient way to do it, but this Java 8 one-liner works

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.