在java 8中将地图映射转换为单个值列表[关闭]

问题描述 投票:-2回答:2

我有一张地图地图:

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流!!

谢谢

java java-8 stream
2个回答
2
投票

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

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]


1
投票

试试这个

 List<Integer> result= new ArrayList<>();
 mapMap.forEach((key, value) -> result.addAll(value.values()));
© www.soinside.com 2019 - 2024. All rights reserved.