简体   繁体   English

java:从数组列表中加入所有哈希图

[英]java: join all hashmaps from an array list

I have an aray list of hashmaps and I'd like to merge these hashmaps into a single one (keys should be unique). 我有一个哈希表的列表,我想将这些哈希表合并为一个(键应该是唯一的)。 How would I have to do it? 我该怎么做? Can anybody give me a hint? 有人可以给我提示吗?

one way to do it would be to create a new instance of HashMap ubermap , iterate over the ArrayList<HashMap> and call putAll() method of ubermap, one map at a time. 一种实现方法是创建一个新的HashMap ubermap实例,遍历ArrayList<HashMap>并调用ubermap的putAll()方法,一次调用一个映射。 A smart optimization would be to give a large initial capacity to ubermap in question so you would avoid many rehash calls. 一个明智的优化是为有问题的ubermap提供较大的初始容量,这样您就可以避免许多重新调用。

You can iterate trought Map.Entry entries from your hash maps. 您可以从哈希映射中迭代trought Map.Entry条目。 You can get entries using entrySet() method. 您可以使用entrySet()方法获取条目。 Code should look like this: 代码应如下所示:

public static <X,Y> Map<X,Y> test(Collection<Map<X,Y>> maps){
    HashMap<X,Y> result = new HashMap<X,Y>();
    for (Map<X,Y> singleMap:maps){
        for(Map.Entry<X,Y> entry:singleMap.entrySet()){
            result.put(entry.getKey(),entry.getValue());
        }
    }
    return result;
}

UPD : Many users wisely advised to use putAll method, but I forgot about it. UPD :许多用户明智地建议使用putAll方法,但我忘了它。 So it will be better to use this code: 因此,最好使用以下代码:

   public static <X,Y> Map<X,Y> test(Collection<Map<X,Y>> maps){
        HashMap<X,Y> result = new HashMap<X,Y>();
        for (Map<X,Y> singleMap:maps){
            result.putAll(singleMap);
        }
        return result;
    }

您应该看看Map.putAll()函数

Map has method putAll(Map m) . Map具有方法putAll(Map m) Iterate over your list and do putAll on a result map for every entry. 遍历您的列表,并在每个条目的结果图上执行putAll

您可以使用for-each循环,并使用HashMap.putAll()从列表中的一个哈希图中一一添加地图。

遍历list并使用putAll()将所有地图添加到生成的地图中

Here is the way: 方法如下:

  1. Create a new (big) hashmap that will contain the merged key-value pairs 创建一个新的(大)哈希表,其中将包含合并的键值对

  2. Iterate through your list 遍历您的清单

  3. For each item of your list, iterate through the hashmap in question 对于列表中的每个项目,请遍历有问题的哈希表

  4. For each value of the hashmap, add the pair in the (big) hashmap 对于哈希表的每个值,将对添加到(大)哈希表中

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM