使用Java 9,您可以将列表映射的所有组合生成为映射列表,如下所示。
在线尝试!
Map<Integer, List<Float>> mapOfLists = new LinkedHashMap<>();
mapOfLists.put(1, List.of(0.1f, 0.2f));
mapOfLists.put(2, List.of(0.3f, 0.4f));
mapOfLists.put(3, List.of(0.5f, 0.6f));
List<Map<Integer, Float>> listOfMaps = mapOfLists.entrySet().stream()
// Stream<List<Map<Integer,Float>>>
.map(entry -> entry.getValue().stream()
// represent list elements as Map<Integer,Float>
.map(element -> Map.of(entry.getKey(), element))
// collect a list of maps
.collect(Collectors.toList()))
// intermediate output
//[{1=0.1}, {1=0.2}]
//[{2=0.3}, {2=0.4}]
//[{3=0.5}, {3=0.6}]
.peek(System.out::println)
// reduce a stream of lists to a single list
// by sequentially multiplying the list pairs
.reduce((list1, list2) -> list1.stream()
// combinations of elements,
// i.e. maps, from two lists
.flatMap(map1 -> list2.stream()
.map(map2 -> {
// join entries of two maps
Map<Integer, Float> map =
new LinkedHashMap<>();
map.putAll(map1);
map.putAll(map2);
return map;
}))
// collect into a single list
.collect(Collectors.toList()))
.orElse(null);
// output a list of map values
listOfMaps.stream().map(Map::values).forEach(System.out::println);
//[0.1, 0.3, 0.5]
//[0.1, 0.3, 0.6]
//[0.1, 0.4, 0.5]
//[0.1, 0.4, 0.6]
//[0.2, 0.3, 0.5]
//[0.2, 0.3, 0.6]
//[0.2, 0.4, 0.5]
//[0.2, 0.4, 0.6]
另请参阅:将列表映射转换为映射列表