我有两个HashMap对象,定义如下:

HashMap<String, Integer> map1 = new HashMap<String, Integer>();
HashMap<String, Integer> map2 = new HashMap<String, Integer>();

我还有第三个HashMap对象:

HashMap<String, Integer> map3;

如何将map1和map2合并为map3?


当前回答

你可以对其他类型使用Collection.addAll(),例如List, Set等。对于Map,您可以使用putAll。

其他回答

你可以对其他类型使用Collection.addAll(),例如List, Set等。对于Map,您可以使用putAll。

HashMap有一个putAll方法。

http://download.oracle.com/javase/6/docs/api/java/util/HashMap.html

您可以使用- addAll方法

http://download.oracle.com/javase/6/docs/api/java/util/HashMap.html

但是总会有这样的问题,如果你的两个哈希映射有相同的键,那么它会用第二个哈希映射的键值覆盖第一个哈希映射的键值。

为了安全起见-更改键值-您可以在键上使用前缀或后缀-(第一个哈希映射使用不同的前缀/后缀,第二个哈希映射使用不同的前缀/后缀)

下面的代码片段采用多个映射并将它们组合起来。

 private static <K, V> Map<K, V> combineMaps(Map<K, V>... maps) {
        if (maps == null || maps.length == 0) {
            return Collections.EMPTY_MAP;
        }

        Map<K, V> result = new HashMap<>();

        for (Map<K, V> map : maps) {
            result.putAll(map);
        }
        return result;
    }

演示示例链接。

map3 = new HashMap<>();

map3.putAll(map1);
map3.putAll(map2);