您可以按照以下方式使用
Stream.reduce
方法。
在线试用!
Map<String, List<String>> map = new LinkedHashMap<>();
map.put("A", List.of("a1", "a2", "a3"));
map.put("B", List.of("b1", "b2", "b3"));
map.put("C", List.of("c1", "c2", "c3"));
List<List<String>> cartesianProduct = map.values().stream()
.map(list -> list.stream().map(Collections::singletonList)
.collect(Collectors.toList()))
.reduce((list1, list2) -> list1.stream()
.flatMap(first -> list2.stream()
.map(second -> Stream.of(first, second)
.flatMap(List::stream)
.collect(Collectors.toList())))
.collect(Collectors.toList()))
.orElse(Collections.emptyList());
int rows = 9;
IntStream.range(0, rows)
.mapToObj(i -> IntStream.range(0, cartesianProduct.size())
.filter(j -> j % rows == i)
.mapToObj(j -> cartesianProduct.get(j).toString())
.collect(Collectors.joining(" ")))
.forEach(System.out::println);
输出:
[a1, b1, c1] [a2, b1, c1] [a3, b1, c1]
[a1, b1, c2] [a2, b1, c2] [a3, b1, c2]
[a1, b1, c3] [a2, b1, c3] [a3, b1, c3]
[a1, b2, c1] [a2, b2, c1] [a3, b2, c1]
[a1, b2, c2] [a2, b2, c2] [a3, b2, c2]
[a1, b2, c3] [a2, b2, c3] [a3, b2, c3]
[a1, b3, c1] [a2, b3, c1] [a3, b3, c1]
[a1, b3, c2] [a2, b3, c2] [a3, b3, c2]
[a1, b3, c3] [a2, b3, c3] [a3, b3, c3]
另请参阅:使用Java递归生成字符串排列