首页 > 解决方案 > 在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 流!

谢谢

标签: javajava-8stream

解决方案


您可以使用以下方法收集所有数值:

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]在上面的代码中


推荐阅读