Skip to content
Advertisement

How to get Cartesian product from multiple lists?

Say I have several List<T>s, I will put them into another list or other collections, so I don’t know how many list<T> I have until I call List<List<T>>.size()

Take below List<Integer> as an example:

JavaScript

How can I get the result of list1*list2*list3*...listn as a Cartesian product?

For example:

JavaScript

should be:

JavaScript

Advertisement

Answer

You can use recursion to achieve it, your base case of recursion is when input is empty then return empty list, else process the remaining elements. E.g.

JavaScript

Output

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