假设Map 本身是可变的,您可以使用类似
map.replaceAll((key, set) -> new HashSet<>(set));
例子:
Map<Integer,Set<Object>> map = new HashMap<>();
map.put(5, Collections.emptySet());
map.put(10, Collections.singleton("foo"));
map.replaceAll((key, set) -> new HashSet<>(set));
map.get(5).add(42);
map.get(10).add("bar");
map.entrySet().forEach(System.out::println);
5=[42]
10=[bar, foo]
当然,您也可以按照复制构造函数约定将new HashSet<>(set) 替换为new TreeSet<>(set) 或通常每个Set 实现类型。当你不能使用复制构造函数时,你必须求助于addAll,例如
map.replaceAll((key, set) -> {
TreeSet<Object> newSet = new TreeSet<>(Comparator.comparing(Object::toString));
newSet.addAll(set);
return newSet;
});
还有另一种选择。无需转换地图的所有值,而是仅按需转换集合,即当您真正想要修改它们并且结果它们没有预期的类型时:
Map<Integer,Set<Object>> map = new HashMap<>();
map.put(5, Collections.emptySet());
map.put(10, Collections.singleton("foo"));
map.computeIfPresent(5, (key,set)->set instanceof HashSet? set: new HashSet<>()).add(42);
map.computeIfPresent(10, (key,set)->set instanceof HashSet?set:new HashSet<>()).add("bar");
map.entrySet().forEach(System.out::println);