If you have a map of lists, you can obtain a Cartesian product of its values using the map and reduce approach. This code can be used with an arbitrary number of lists.
Try it online!
// a map of lists
Map<String, List<String>> map = new TreeMap<>();
map.put("A", Arrays.asList("A1", "A2"));
map.put("B", Arrays.asList("B1", "B2"));
map.put("C", Arrays.asList("C1", "C2"));
// cartesian product of the map values
List<List<String>> cp = map.values().stream()
// represent each element of a list as a singleton list
.map(list -> list.stream().map(Arrays::asList)
// Stream<List<List<String>>>
.collect(Collectors.toList()))
// summation of pairs of list into a single list
.reduce((list1, list2) -> list1.stream()
// combinations of inner lists
.flatMap(inner1 -> list2.stream()
// concatenate into a single list
.map(inner2 -> Stream.of(inner1, inner2)
.flatMap(List::stream)
.collect(Collectors.toList())))
// list of combinations
.collect(Collectors.toList()))
// otherwise an empty list
.orElse(Collections.emptyList());
// output
map.forEach((k, v) -> System.out.println(k + ": " + v));
cp.forEach(System.out::println);
Output:
A: [A1, A2]
B: [B1, B2]
C: [C1, C2]
[A1, B1, C1]
[A1, B1, C2]
[A1, B2, C1]
[A1, B2, C2]
[A2, B1, C1]
[A2, B1, C2]
[A2, B2, C1]
[A2, B2, C2]
See also: How to create cartesian product over arbitrary groups of numbers in Java?