What is the most efficient way to compare keys of two HashMaps?

Viewed 79

I want to compare 2 HashMaps to sum the values for any common keys between them:

HashMap<Integer, Integer> map1
HashMap<Integer, Integer> map2

What would be the most efficient way to do this?

1 Answers
  1. Get the keySet of both maps (O(n)).
  2. Compute the intersection among them (O(n)).
  3. For the common keys found in above set, get the values from both maps and sum them (O(n)).

Total time complexity - O(n).

Set<Integer> commonKeys = new HashSet<>(map1.keySet());
commonKeys.retainAll(map2.keySet());

Map<Integer, Integer> result = commonKeys.stream()
            .collect(Collectors.toMap(Function.identity(), 
                    k -> map1.get(k) + map2.get(k)));
Related