views:

1540

answers:

5

Do you know some neat Java libaries that allow you to make cartesian product of two (or more) sets?

For example: I have tree sets. One with objects of class Person, second with objects of class Gift and third with objects of class GiftExtension.

I want to generate one set containing all possible triples Person-Gift-GiftExtension.

The number of sets might vary so I cannot do this in nested foreach loop. Under some conditions my application needs to make a product of Person-Gift pair, sometimes it is triple Person-Gift-GiftExtension, sometimes there might even be sets Person-Gift-GiftExtension-GiftSecondExtension-GiftThirdExtension, etc.

+4  A: 
Michael Myers
I think this is a really great way to deal with Pairs. If he does not know if he might need pairs, triples, quadrupels... then it's not directly fitting, but he could use Pair<Pair<Person,Gift>,GiftExtension> i think.
Brian Schimmel
A: 

What you want is similar to this

Aziz
+2  A: 

The number of sets might vary so I cannot do this in nested foreach loop.

Two hints:

  • A x B x C = A x (B x C)
  • Recursion
Michael Borgwardt
+1  A: 

The memory (and processing) footprint needed for a Cartesian product can get out of hand pretty quickly. The naive implementation can exhaust memory and take a lot of time. It would be nice to know the operations you are planning to perform in such a set, in order to suggest a implementation strategy.

In any case, do something like Sets.SetView on google collections. This is a set that gets backed by other sets as they get added. The idea for their problem there is to avoid the addAll call. The idea for your problem is to avoid making NxMxK adds to a set.

Google collections can be found here and the mentioned class is here

Marcelo Morales
+2  A: 

Yes, there is Functional Java.

For a set (s):

s.bind(P.p2(), s);

note that fj.data.Set does not have a bind method, but it does have toStream() and iterableSet(Iterable) to convert to/from fj.data.Stream which does have a bind method.
Apocalisp