java - 在java 8中将地图转换为单个值列表
问题描述
我有一张地图:
Map<Integer,Map<String,Integer>>
我需要将此地图展平为值列表:
Map<String,Integer> map1 = new HashMap<>();
Map<String,Integer> map2 = new HashMap<>();
map1.putIfAbsent("ABC",123);
map1.putIfAbsent("PQR",345);
map1.putIfAbsent("XYZ",567);
map2.putIfAbsent("ABC",234);
map2.putIfAbsent("FGH",789);
map2.putIfAbsent("BNM",890);
Map<Integer,Map<String,Integer>> mapMap = new HashMap();
mapMap.putIfAbsent(0,map1);
mapMap.putIfAbsent(1,map2);
预期输出:123
345
567
234
789
890
我需要不同的解决方案,包括 java 8 流!
谢谢
解决方案
您可以使用以下方法收集所有数值:
List<Integer> numbers = mapMap
.values() //all `Map` values
.stream()
.map(Map::values) //map each inner map to the collection of its value
.flatMap(Collection::stream) // flatten all inner value collections
.collect(Collectors.toList()); //collect all values into a single list
numbers
包含[345, 123, 567, 890, 234, 789]
在上面的代码中
推荐阅读
- r - 如何在 R Shiny select-Input 中获取特定值而不是选择的打印名称
- c++ - 在 Dev C++ 的默认启动代码片段中添加动态注释
- go - 无法在 GCP 中指定 gflag
- arrays - 如何将键添加到数组数组中的值?
- javascript - 手机和电脑打印页面不同
- r - 如何在 R 中生成不同的对?
- mql4 - 为什么 ChartApplyTemplate 只在第二次尝试时起作用?
- javascript - 使用 Bootstrap 模板闪烁的 Sticky Nav 活动按钮
- node.js - 如何在 Node.js 中捕获(或抑制)“PayloadTooLargeError:请求实体太大”错误?
- google-cloud-dataflow - 核心和工人之间是什么关系?