0

我有两个地图列表。

List<Map<String,String>> catDataToCache = new ArrayList();
List<Map<String,String>> catDataToCache2 = new ArrayList();

每张地图都是这样的

map('referer'=>'abc.com','category'=>'def.com')

我必须合并这两个。我试过List.addAll();但是我得到一个乱码的集合。

4

2 回答 2

3

我相信您正在尝试合并来自两个或多个Maps 的映射。如果是这样,您可以在Map#putAll()不涉及Lists 的情况下使用它,除非Maps 实际存储在其中,这似乎不太可能。

Map<String, String> map1 = new HashMap<String, String>();
map1.put("referrer", "abc.com");

Map<String, String> map2 = new HashMap<String, String>();
map2.put("category", "def.com");

Map<String, String> map3 = new HashMap<String, String>();

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

for (Map.Entry<String, String> mapping : map3.entrySet()) {
    System.out.println(mapping.getKey() + " = " + mapping.getValue());
}

输出

category = def.com
referrer = abc.com


如果您实际上Map是在 a 中获取 s List,只需对其进行迭代并按putAll()上面所示为 each使用Map。如果有多个这样的 s,则为每个List重复循环。Iterator

List<Map<String,String>> listOfMaps = new ArrayList<Map<String,String>>();

// initialize map1, map2, map3 same as above

listOfMaps.add(map1);
listOfMaps.add(map2);

for (Iterator<Map<String, String>> iterator =
                        listOfMaps.iterator(); iterator.hasNext();) {
    map3.putAll(iterator.next());
}

for (Map.Entry<String, String> mapping : map3.entrySet()) {
    System.out.println(mapping.getKey() + " = " + mapping.getValue());
}
于 2013-10-07T13:23:04.360 回答
1
    List<Map<String,String>> catDataToCache = new ArrayList<Map<String, String>>();
    List<Map<String,String>> catDataToCache2 = new ArrayList<Map<String, String>>();

    List<Map<String,String>> mergedDataToCache = new ArrayList<Map<String, String>>();

    mergedDataToCache.addAll(catDataToCache);
    mergedDataToCache.addAll(catDataToCache2);

    Map<String,String> mergedMap= new HashMap<String, String>();

    for(Map<String,String> map:mergedDataToCache){
        mergedMap.putAll(map);
    }
于 2013-10-07T13:23:33.407 回答