Java Guava CartesianProduct

4.5k Views Asked by At

I am exploring Java Guava Library by writing small snippets of code. Here is what I wrote for finding the cartesian product of n-sets. Documentation here

//allLists populated above
...
List<Set> interimList = new ArrayList<Set>();
for(List<String> tmp : allLists) //converting List<List> to List<Set> 
{
    Set interimSet   = new HashSet(tmp);
    interimList.add(interimSet);
}
System.out.println(interimList);
Sets.cartesianProduct(interimList);

But this is not compiling. The last line Sets.cartesianProduct is not accepting List<Set>. But according to documentation isn't that its signature?

public static <B> Set<List<B>> cartesianProduct(List<? extends Set<? extends B>> sets)

ERROR MESSAGE: Cannot Resolve method cartesianProduct(java.util.List<java.util.Set)

1

There are 1 best solutions below

0
On BEST ANSWER

The problem is you have created a raw Set, instead of a generic one.

What happens is you're trying to pass a List<Set<Object extends String>> to the Sets.cartesianProduct() and this is why you're receiving a compile-type error.

This compiles:

List<Set<String>> interimList = new ArrayList<Set<String>>();
//converting List<List<String>> to List<Set<String>>
for (List<String> tmp : allLists) { 
    Set<String> interimSet   = new HashSet<String>(tmp);
    interimList.add(interimSet);
}
System.out.println(interimList);
Sets.cartesianProduct(interimList);