简体   繁体   English

Java:两个数组的每种组合

[英]Java: every combination of two arrays

I have 2 arrays (T0, T1, T2) & (R1,R2,R3) I want all 27 combinations of them for example: 我有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
....

I know how to do it with 3 for loops but I need something more flexible that can work with different number of array sizes (eg (T0,..T8) & (R1, R2)). 我知道如何使用3个for循环来做到这一点,但是我需要一些更灵活的东西,可以使用不同数量的数组大小(例如(T0,.. T8)和(R1,R2))。

Thanks 谢谢

Why 3 for-loops? 为什么要3个for循环?

for(int i : array1) {
    for(int j : array2) {
        combinations.add(new Combination(i, j));
    }
}

Just as an example... 举个例子...

In Java 8, you could flatmap a stream of elements and build pairs of them like this: 在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);

Easy way would be to convert the arrays into Sets and then use Google Guava's http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/Sets.html#cartesianProduct(java.util.List) 简单的方法是将数组转换为Set,然后使用Google Guava的http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/Sets.html#cartesianProduct(java.util 。列表)

To get the cartesian product. 获得笛卡尔积。 It has a convinient method for Array -> Set: newHashSet(E... elements) 它有一个方便的Array-> Set方法:newHashSet(E ... elements)

You should consider to use "standard" libarys to not reinvent the wheel. 您应该考虑使用“标准”库而不是重新发明轮子。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM