Note: A Set
is a collection that contains no duplicate elements. If you have duplicate elements in different sets, then each set from the Cartesian product will contain only one of them.
You can create a generic method to get a Cartesian product and specify the types of collections to store it. For example, a Set
or a List
.
Cartesian product using map and reduce approach
Try it online!
public static void main(String[] args) {
List<Set<String>> sets = List.of(
Set.of("A", "B"), Set.of("B", "C"), Set.of("C", "A"));
List<Set<String>> cpSet = cartesianProduct(HashSet::new, sets);
List<List<String>> cpList = cartesianProduct(ArrayList::new, sets);
// output, order may vary
System.out.println(toString(cpSet));
//ABC, AB, AC, AC, BC, BA, BC, BCA
System.out.println(toString(cpList));
//ABC, ABA, ACC, ACA, BBC, BBA, BCC, BCA
}
/**
* @param cols the input collection of collections
* @param nCol the supplier of the output collection
* @param <E> the type of the element of the collection
* @param <R> the type of the return collections
* @return List<R> the cartesian product of the multiple collections
*/
public static <E, R extends Collection<E>> List<R> cartesianProduct(
Supplier<R> nCol, Collection<? extends Collection<E>> cols) {
// check if the input parameters are not null
if (nCol == null || cols == null) return null;
return cols.stream()
// non-null and non-empty collections
.filter(col -> col != null && col.size() > 0)
// represent each element of a collection as a singleton collection
.map(col -> col.stream()
.map(e -> Stream.of(e).collect(Collectors.toCollection(nCol)))
// Stream<List<R>>
.collect(Collectors.toList()))
// summation of pairs of inner collections
.reduce((col1, col2) -> col1.stream()
// combinations of inner collections
.flatMap(inner1 -> col2.stream()
// concatenate into a single collection
.map(inner2 -> Stream.of(inner1, inner2)
.flatMap(Collection::stream)
.collect(Collectors.toCollection(nCol))))
// list of combinations
.collect(Collectors.toList()))
// otherwise an empty list
.orElse(Collections.emptyList());
}
// supplementary method, returns a formatted string
static <E extends String> String toString(List<? extends Collection<E>> cols) {
return cols.stream().map(col -> String.join("", col))
.collect(Collectors.joining(", "));
}
See also: Cartesian product of an arbitrary number of sets