![](/img/trans.png)
[英]Gson merging JsonObject throws java.lang.UnsupportedOperationException
[英]Merging Maps containing Sets throws UnsupportedOperationException
這是代碼:
private static Map<String, Set<String>> merge(Map<String, Set<String>> m1, Map<String, Set<String>> m2) {
Map<String, Set<String>> mx = new HashMap<String, Set<String>>();
for (Entry<String, Set<String>> entry : m1.entrySet()) {
Set<String> otherMapValue = m2.get(entry.getKey());
if (otherMapValue == null) {
mx.entrySet().add(entry);
} else {
Set<String> merged = new HashSet<String>();
merged.addAll(entry.getValue());
merged.addAll(otherMapValue);
mx.put(entry.getKey(), merged);
}
}
return mx;
}
這將引發以下錯誤:
Exception in thread "main" java.lang.UnsupportedOperationException
at java.util.AbstractCollection.add(Unknown Source)
at algorithms.NetworkBuilder.merge(NetworkBuilder.java:86)
at algorithms.NetworkBuilder.build(NetworkBuilder.java:38)
at algorithms.Main.main(Main.java:35)
我只找到了不包含集合的地圖解決方案,它們對我不起作用,因為如果兩個地圖中都出現鍵,我還需要合並集合。
我要做的是創建一個新映射,其中包含兩個映射中的一個或兩個的每個鍵都映射到在原始兩個映射中映射到的列表的並集。
返回此映射中包含的映射的Set視圖。 [...]集合支持元素刪除,該元素通過Iterator.remove,Set.remove,removeAll,retainAll和clear操作從映射中刪除相應的映射。 它不支持add或addAll操作。
嘗試使用mx.put(entry.getKey(), entry.getValue())
代替mx.entrySet().add(entry)
。
如果允許使用第三方庫,請考慮使用Guava的Multimap
。
[
Multimap
的]與集合地圖的比較
Multimap
通常用於否則會出現Map<K, Collection<V>>
。
Multimap<String, String> m1 = ...
Multimap<String, String> m2 = ...
m1.putAll(m2); // merged!
您的代碼問題就在行中
mx.entrySet().add(entry);
您使用的集合僅支持刪除操作: http : //docs.oracle.com/javase/7/docs/api/java/util/Map.html#entrySet()
您可能需要將該行更改為
mx.put(entry.getKey(), entry.getValue());
另外,您的方法不會考慮m2
的鍵,而不會考慮m1
的鍵。 您可能還想遍歷m2.entrySet()
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.