Java tutorial
//package com.java2s; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class Main { public static List[] cartesianProduct(List left, List[] right) { if (right.length == 0) { return (List[]) left.toArray(new List[] {}); } List result = new ArrayList(); for (Object elementLeft : left) { for (Object elementRight : right[0]) { List resultElement = new ArrayList(); if (elementLeft instanceof List) { resultElement = new ArrayList((List) elementLeft); } else { resultElement.add(elementLeft); } resultElement.add(elementRight); result.add(resultElement); } } return cartesianProduct(result, Arrays.asList(right).subList(1, right.length).toArray(new List[] {})); } public static List[] cartesianProduct(List[] list) { return cartesianProduct(list[0], Arrays.asList(list).subList(1, list.length).toArray(new List[] {})); } }