Iteratively compute the Cartesian product of an arbitrary number of sets

I’ve written a solution that doesn’t require you to fill up a large collection in memory. Unfortunately, the code required is hundreds of lines long. You may have to wait until it appears in the Guava project (https://github.com/google/guava), which I hope will be by the end of the year. Sorry. 🙁

Note that you may not need such a utility if the number of sets you’re cartesian-producting is a fixed number known at compile time — you could just use that number of nested for loops.

EDIT: the code is released now.

Sets.cartesianProduct()

I think you’ll be very happy with it. It only creates the individual lists as you ask for them; doesn’t fill up memory with all MxNxPxQ of them.

If you want to inspect the source, it’s here.

Enjoy!

Leave a Comment