Skip to content
Advertisement

Implement Cartesian product of several collections by Java Stream

Right now I can only implement the Cartesian product of two collections, here is the code:

JavaScript

This code works fine in IntelliJ, but not in Eclipse. Both with compiler compliance level of 1.8:

JavaScript

Here is Pair.java:

JavaScript

How to fix this error?

Is there an elegant way to implement the Cartesian product of several collections? Suppose we have class tuple.

Advertisement

Answer

Eclipse has problems with type inference. If you add a type hint .<Pair<T1,T2>>flatMap, it compiles fine.

If I may suggest a different approach, consider making your cartesianProduct not do the entire stream and collection but merely be a helper for flatMap:

JavaScript

Now you only need to create a Pair if you want the result to contains Pairs and you can do a higher-order cartesian product by applying flatMap several times:

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement