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?
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?
O(n)).O(n)).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)));