注意:Set
是不包含重复元素的集合。如果在不同的集合中有重复元素,则笛卡尔积中的每个集合将仅包含其中一个。
您可以创建一个通用方法来获取笛卡尔积并指定存储它的集合类型。例如,Set
或List
。
使用map和reduce方法的笛卡尔积
在线试用!
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);
System.out.println(toString(cpSet));
System.out.println(toString(cpList));
}
public static <E, R extends Collection<E>> List<R> cartesianProduct(
Supplier<R> nCol, Collection<? extends Collection<E>> cols) {
if (nCol == null || cols == null) return null;
return cols.stream()
.filter(col -> col != null && col.size() > 0)
.map(col -> col.stream()
.map(e -> Stream.of(e).collect(Collectors.toCollection(nCol)))
.collect(Collectors.toList()))
.reduce((col1, col2) -> col1.stream()
.flatMap(inner1 -> col2.stream()
.map(inner2 -> Stream.of(inner1, inner2)
.flatMap(Collection::stream)
.collect(Collectors.toCollection(nCol))))
.collect(Collectors.toList()))
.orElse(Collections.emptyList());
}
static <E extends String> String toString(List<? extends Collection<E>> cols) {
return cols.stream().map(col -> String.join("", col))
.collect(Collectors.joining(", "));
}
另请参见:任意数量集合的笛卡尔积