下面是代码:
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)我只找到了不包含集合的映射的解决方案,它们不适合我,因为如果两个映射中都出现了键,我也需要合并这些集合。
我想要做的是创建一个新的映射,其中包含两个映射中的一个或两个映射的每个键都映射到原始两个映射中映射到的列表的合并。
发布于 2015-08-13 19:56:00
返回此映射中包含的映射的集合视图。..。集合支持元素删除,它通过Iterator.remove、Set.remove、removeAll、retainAll和clear操作从映射中删除对应的映射。它不支持添加或addAll操作.
尝试mx.put(entry.getKey(), entry.getValue())而不是mx.entrySet().add(entry)。
如果允许使用第三方库,请考虑使用番石榴的Multimap。
Multimap与馆藏地图的比较Multimap通常用于那些本来会出现Map<K, Collection<V>>的地方。
Multimap<String, String> m1 = ...
Multimap<String, String> m2 = ...
m1.putAll(m2); // merged!https://stackoverflow.com/questions/31997116
复制相似问题