nicolasmanic
nicolasmanic

Reputation: 19

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:

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 (e.g. (T0,..T8) & (R1, R2)).

Thanks

Upvotes: 0

Views: 2724

Answers (3)

Martin Seeler
Martin Seeler

Reputation: 6982

In Java 8, you could flatmap a stream of elements and build pairs of them like this:

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);

Upvotes: 0

Bene
Bene

Reputation: 734

Why 3 for-loops?

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

Just as an example...

Upvotes: 1

Mirco
Mirco

Reputation: 3016

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)

To get the cartesian product. It has a convinient method for Array -> Set: newHashSet(E... elements)

You should consider to use "standard" libarys to not reinvent the wheel.

Upvotes: 0

Related Questions