注意:Set 是不包含重复元素的集合。如果您在不同的集合中有重复的元素,那么笛卡尔积中的每个集合将只包含其中一个。
您可以创建一个通用方法来获取笛卡尔积并指定要存储它的集合类型。例如,Set 或 List。
使用map和reduce方法的笛卡尔积
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(", "));
}
另见:Cartesian product of an arbitrary number of sets