【问题标题】:Merging Maps containing Sets throws UnsupportedOperationException合并包含 Set 的 Map 会引发 UnsupportedOperationException
【发布时间】:2015-11-06 22:41:39
【问题描述】:

代码如下:

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)

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

【问题讨论】:

    标签: java merge hashmap java-8 hashset


    【解决方案1】:

    Map::entrySet:

    返回此映射中包含的映射的 Set 视图。 [...] 套装支持 元素移除,即从地图中移除对应的映射, 通过 Iterator.remove、Set.remove、removeAll、retainAll 和 clear 操作。 不支持 add 或 addAll 操作。

    尝试使用mx.put(entry.getKey(), entry.getValue()) 而不是mx.entrySet().add(entry)

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

    将 [Multimaps] 与集合地图进行比较

    Multimaps 常用于Map&lt;K, Collection&lt;V&gt;&gt; 否则会出现。

    Multimap<String, String> m1 = ...
    Multimap<String, String> m2 = ...
    
    m1.putAll(m2); // merged!
    

    【讨论】:

      【解决方案2】:

      你的代码问题出在一行

      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()

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-04-29
        • 2016-07-13
        • 2017-05-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多