首页 > 解决方案 > 使用地图列表创建合并地图

问题描述

我是java新手,所以寻求专家的帮助。任何帮助将不胜感激,并为我提供学习新事物的空间。

我想从另一个地图列表(列表)创建地图列表(结果列表),其中单个地图(键)包含作为地图列表键的值(map1,map2,map3 ...等等)。像下面的例子

Map<String, String> keys = new HashMap<>();
keys.put("Animal","Cow");
keys.put("Bird","Eagle");

Map<String, String> map1 =new HashMap<>();
map1.put("Cow","Legs");
m1.put("Eagle","Wings");

Map<String, String> map2 = new HasMap<>();
map2.put("Cow","Grass");
map2.put("Eagle","Flesh");

List<Map<String, String>> list= new ArrayList<>();
list.add(map1);
list.add(map2); // there could be more

List<Map<String, String>> resultList= new ArrayList<>();
for(Map<String, String> eachMap: listOfMaps){
     Map<String, String> mergedMap = new HasMap<>();
     //help me here
}

现在我希望第一个 map(keys) 的值作为第二个 map(map1) 和第三个 map(map2) 的值的每个新 map(mergedMap) 的键,依此类推。

所需的输出应该像

{ Cow : Legs, Eagle : Wings }
{ Cow : Grass, Eagle : Flesh }
//more

标签: javacollectionsstream

解决方案


另一种使用流的方法。

Collection<String> vals = keys.values();
resultList = list.stream()
    .map(eachMap -> vals.stream()
            .filter(eachMap::containsKey)
            .collect(Collectors.toMap(Function.identity(), eachMap::get)))
     .collect(Collectors.toList());
 
System.out.println(resultList);

注意:filter在创建地图之前检查该值是否存在于地图中。


推荐阅读