从ArrayList存储和检索hashmap值?

时间:2017-06-05 10:11:28

标签: java arrays arraylist hashmap

我必须采用集合的联合(如果有n个数,那么集将是> n *(n-1)/ 2)

我做了什么:

我已经拍摄了地图列表,然后将值放在地图

给定:n =列表大小,l =地图长度

List<Map<Integer, String>> maps = new ArrayList<Map<Integer, String>>(); 
      for(int i=0;i<n;i++){
          Map<Integer,String> myMap1 = new HashMap<Integer, String>(); 
           int l=in.nextInt();
           for(int j=0;j<l;j++){
               int num=in.nextInt();
               myMap1.put(num, "Val0");
           }
           //System.out.println(myMap1);
           maps.add(i,myMap1);
           //System.out.println(maps.get(i));
      }

我想要的:

现在我想用其他地图添加每张地图,以便我可以找到联盟

请帮助并且不要Downvote它,它不是重复的Q我已经为答案提供了帮助而我没有得到,因为我得到了相反的结果link description here

1 个答案:

答案 0 :(得分:0)

你在寻找这样的东西:

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

public class MapUnion {

    /**
     * This method adds all entries in all maps and return it as single map. It
     * takes Collection of elements of type Map<K, V>
     * 
     * @param maps - the Collection of maps, to sum all the entries
     * @return map containig "union" of all entries from all of the supplied maps
     */
    public <K, V> Map<K, V> unionAllMaps(Collection<Map<K, V>> maps) {
        return unionAllMaps(maps.toArray(new Map[maps.size()]));
    }

    /**
     * This method adds all entries in all maps and return it as single map. It
     * takes any numner of elements of type Map<K, V>. You can invoke it using
     * eg unionAllMaps(map1, map2, map3); the ... denotes, that all parameters
     * will be automatically converted to an array
     * 
     * @param maps - the Array of maps, to sum all the entries
     * @return map containig "union" of all entries from all of the supplied maps
     */
    public <K, V> Map<K, V> unionAllMaps(Map<K, V>... maps) {
        HashMap<K, V> union = new HashMap<K, V>();
        for (Map<K, V> map : maps) {
            union.putAll(map);
        }
        return union;
    }

    public static void main(String[] args) {
        new MapUnion().test();
    }

    public void test() {
        HashMap<Integer, String> map1 = new HashMap<Integer, String>();
        map1.put(1, "1");
        map1.put(2, "2");
        HashMap<Integer, String> map2 = new HashMap<Integer, String>();
        map1.put(2, "2");
        map1.put(3, "3");

        ArrayList<Map<Integer, String>> maps = new ArrayList<Map<Integer, String>>();
        maps.add(map1);
        maps.add(map2);

        Map<Integer, String> union = unionAllMaps(maps);

        System.out.println(union);
    }
}

将打印:

{1 = 1,2 = 2,3 = 3}

但是如果在这些地图中有相同的键具有不同的值,会发生什么?在这种方法中,最后一个值将覆盖前一个值,但这是正确的吗?