java—比较两个哈希Map的键最有效的方法是什么

fzwojiic  于 2021-06-29  发布在  Java
关注(0)|答案(1)|浏览(282)

我想比较2个hashmap,以便对它们之间的任何公共键的值求和hashmap<integer,integer>map1 hashmap<integer,integer>map2最有效的方法是什么

taor4pac

taor4pac1#

获取两个Map的键集( O(n) ).
计算它们之间的交集( O(n) ).
对于上述集合中的公共键,从两个Map中获取值并求和( O(n) ).
总时间复杂度- 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)));

相关问题