您可以使用Stream.reduce方法如下。
Try it online!
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()
// represent each list element as a singleton list
.map(list -> list.stream().map(Collections::singletonList)
.collect(Collectors.toList()))
// reduce the stream of lists to a single list by
// sequentially summing pairs of elements of two lists
.reduce((list1, list2) -> list1.stream()
// combinations of inner lists
.flatMap(first -> list2.stream()
// merge two inner lists into one
.map(second -> Stream.of(first, second)
.flatMap(List::stream)
.collect(Collectors.toList())))
// list of combinations
.collect(Collectors.toList()))
// List<List<String>>
.orElse(Collections.emptyList());
// column-wise output
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]
另见:String permutations using recursion in Java