[英]Java: every combination of two arrays
我有2個數組(T0,T1,T2)&(R1,R2,R3)我想要它們的所有27個組合,例如:
R1-T1, R1-T2, R1-T3
R1-T1, R1-T2, R2-T3
R1-T1, R1-T2, R3-T3
R1-T1, R2-T2, R1-T3
R1-T1, R2-T2, R2-T3
R1-T1, R2-T2, R3-T3
....
我知道如何使用3個for循環來做到這一點,但是我需要一些更靈活的東西,可以使用不同數量的數組大小(例如(T0,.. T8)和(R1,R2))。
謝謝
為什么要3個for循環?
for(int i : array1) {
for(int j : array2) {
combinations.add(new Combination(i, j));
}
}
舉個例子...
在Java 8中,您可以對元素流進行平面映射,並構建成對的元素,如下所示:
final List<Integer> first = Arrays.asList(1, 2, 3);
final List<Integer> second = Arrays.asList(1, 2, 3);
first.stream()
.flatMap(x -> second.stream().map(y -> Tuple.tuple(x, y)))
.forEach(System.out::println);
簡單的方法是將數組轉換為Set,然后使用Google Guava的http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/Sets.html#cartesianProduct(java.util 。列表)
獲得笛卡爾積。 它有一個方便的Array-> Set方法:newHashSet(E ... elements)
您應該考慮使用“標准”庫而不是重新發明輪子。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.