Suppose I have 3 lists: ['q','w'], ['a','s'], ['z','x']. How to get a list of possible combinations out of these lists? So I get a list [['q','a','z'],['q','s','z']] and such. I made a method for two, but can't figure one for N lists:
static <E> ArrayList combine(ArrayList<E> one,ArrayList<E> two)
{
ArrayList<ArrayList<E>> combs=new ArrayList<ArrayList<E>>();
for(E e:one)
{
for(E e2:two)
{
ArrayList ps=new ArrayList();
ps.add(e);
ps.add(e2);
combs.add(ps);
}
}
return combs;
}
I found out that this is done by Guava's Sets.cartesianProduct.
For the lazy (using Guava):
Set<List<String>> result = Sets.cartesianProduct(
ImmutableSet.of("q", "w"),
ImmutableSet.of("a", "s"),
ImmutableSet.of("z", "x")
);
System.out.println(result);
output:
[
[q, a, z],
[q, a, x],
[q, s, z],
[q, s, x],
[w, a, z],
[w, a, x],
[w, s, z],
[w, s, x]
]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With