I have the following collection type:
Map> map;
I would like to create unique combinations of each o
A solution that mainly operates on lists, making things a lot simpler. It does a recursive call in flatMap
, keeping track of the elements that have already been combined, and the collections of elements that are still missing, and offers the results of this nested recursive construction as a stream of lists:
import java.util.*;
import java.util.stream.Stream;
public class CartesianProduct {
public static void main(String[] args) {
Map> map =
new LinkedHashMap>();
map.put("A", Arrays.asList("a1", "a2", "a3", "a4"));
map.put("B", Arrays.asList("b1", "b2", "b3"));
map.put("C", Arrays.asList("c1", "c2"));
ofCombinations(map.values()).forEach(System.out::println);
}
public static Stream> ofCombinations(
Collection extends Collection> collections) {
return ofCombinations(
new ArrayList>(collections),
Collections.emptyList());
}
private static Stream> ofCombinations(
List extends Collection> collections, List current) {
return collections.isEmpty() ? Stream.of(current) :
collections.get(0).stream().flatMap(e ->
{
List list = new ArrayList(current);
list.add(e);
return ofCombinations(
collections.subList(1, collections.size()), list);
});
}
}