Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
421 views
in Technique[技术] by (71.8m points)

java - Get a list of combinations of lists' elements

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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] ]


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...