[英]Java - convert unmodifiable sets in a map(key, set) to modifaible
我實現了一個返回Map<key,Set<objects>>
的 function ,當我調用這個 function 時,它返回類型為不可修改的集合。
我需要對這個集合做一些操作,如何在最佳實踐中將它們轉換為可修改的集合? 否則我得到
Exception in thread "main" java.lang.UnsupportedOperationException
提前致謝。
假設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 的所有值,不如僅按需轉換集合,即當您實際想要修改它們但結果卻沒有預期的類型時:
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);
您可以將 原始集復制到另一個可以修改的集。
像這樣的東西:
Set<YourType> newSet = unmodifiableSet
.stream()
.collect(Collectors.toSet());
// Or maybe...
Set<YourTYpe> otherSet = new HashSet<>();
otherSet.addAll(unmodifiableSet);
然后,您可以毫無問題地修改新列表,並將其重新分配到 map。
對於HashSet
:
Set<Type> modifiable = new HashSet<>(unmodifiable);
對於TreeSet
:
SortedSet<Type> modifiable = new TreeSet<>(unmodifiable);
對於LinkedHashSet
:
Set<Type> modifiable = new LinkedHashSet<>(unmodifiable);
如果您使用沒有此類構造函數的精美 Set 實現:
Set<Type> modifiable = new MyFancySet<>();
modifiable.addAll(unmodifiable);
您可以使用Streams
執行此操作:
map
是您原來的 map (例如Map<Integer, ImmutableSet<Object>> map;
)
Map<Integer, Set<Object>> mutableMap = map.entrySet()
.stream()
.collect(Collectors.toMap(Map.Entry::getKey, Sets::newHashSet));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.