在 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]

试试这个

List<Integer> result= new ArrayList<>();
mapMap.forEach((key, value) -> result.addAll(value.values()));

最新更新