java - 使用地图列表创建合并地图
问题描述
我是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
解决方案
另一种使用流的方法。
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
在创建地图之前检查该值是否存在于地图中。
推荐阅读
- python - 带有多级解析器/子解析器的 Argparse 可选参数
- git - Git:可以在 .gitconfig 中引用来自 .gitconfig 的变量吗?
- c++ - 在 Microsoft Access SQL 中调用自定义 DLL 函数时传递的内存地址无效
- java - 在实用程序类中反射方法并在 Java 中使用可变参数调用它们
- c++ - C++ 中的命名空间重构
- ruby - 使用 Action Mailbox 和 Elastic Beanstalk 未收到从 SendGrid 到 Rails 6 应用程序的电子邮件中继
- ruby-on-rails - 删除 Rails 中的所有资源路由
- azure-active-directory - 通过 .net core 2.1 连接到 Azure 资源的最佳方式
- javascript - Swiper:根据幻灯片更改主体的背景颜色
- c++ - 结构成员在访问时被清除