合并包含集合的地图会抛出UnsupportedOperationException

时间:2015-08-13 19:46:03

标签: java merge hashmap java-8 hashset

以下是代码:

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)

我只找到了包含不包含集合的地图的解决方案,它们对我不起作用,因为如果两个地图中都出现了一个键,我还需要合并这些集合。
我想要做的是创建一个新映射,其中包含两个映射中的一个或两个的每个键映射到它在原始两个映射中映射到的列表的并集。

1 个答案:

答案 0 :(得分:4)

Map::entrySet

  

返回此映射中包含的映射的Set视图。 [...]集支持   元素删除,从地图中删除相应的映射,   通过Iterator.remove,Set.remove,removeAll,retainAll和clear   操作。 它不支持add或addAll操作。

尝试使用mx.put(entry.getKey(), entry.getValue())代替mx.entrySet().add(entry)

如果您被允许使用第三方库,请考虑使用Guava的Multimap

  

[Multimap s]与集合地图的比较

     

Multimap通常用于Map<K, Collection<V>>的地方   否则会出现。

Multimap<String, String> m1 = ...
Multimap<String, String> m2 = ...

m1.putAll(m2); // merged!