在Java中实现笛卡尔积可以使用循环嵌套、递归、流等方法。以下是几种常见的实现方法:
List<List<Integer>> sets = Arrays.asList(
Arrays.asList(1, 2),
Arrays.asList(3, 4),
Arrays.asList(5, 6)
);
List<List<Integer>> cartesianProduct = new ArrayList<>();
for (int i = 0; i < sets.get(0).size(); i++) {
for (int j = 0; j < sets.get(1).size(); j++) {
for (int k = 0; k < sets.get(2).size(); k++) {
List<Integer> tuple = Arrays.asList(sets.get(0).get(i), sets.get(1).get(j), sets.get(2).get(k));
cartesianProduct.add(tuple);
}
}
}
public static List<List<Integer>> cartesianProduct(List<List<Integer>> sets, int index) {
if (index == sets.size() - 1) {
return sets.get(index).stream()
.map(Collections::singletonList)
.collect(Collectors.toList());
}
List<List<Integer>> result = new ArrayList<>();
for (int i : sets.get(index)) {
for (List<Integer> rest : cartesianProduct(sets, index + 1)) {
List<Integer> tuple = new ArrayList<>();
tuple.add(i);
tuple.addAll(rest);
result.add(tuple);
}
}
return result;
}
List<List<Integer>> sets = Arrays.asList(
Arrays.asList(1, 2),
Arrays.asList(3, 4),
Arrays.asList(5, 6)
);
List<List<Integer>> cartesianProduct = sets.stream()
.reduce((a, b) -> a.stream()
.flatMap(i -> b.stream().map(j -> new ArrayList<>(Arrays.asList(i, j))))
.collect(Collectors.toList()))
.orElse(Collections.emptyList());
以上是几种常见的Java实现笛卡尔积的方法,具体选择哪种方法取决于具体的需求和场景。