Skip to content

Instantly share code, notes, and snippets.

@cdarlint

cdarlint/product.java

Last active Jan 18, 2019
Embed
What would you like to do?
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class arraycalc {
public static void main(String[] args) {
List<List<Object>> n = new ArrayList();
n.add(Arrays.asList("A", "B", "C"));
n.add(Arrays.asList(4, 5));
n.add(Arrays.asList(0));
System.out.println(product(n));
}
public static <T> List<List<T>> product(List<List<T>> b) {
List<List<T>> result = new ArrayList<List<T>>();
List<List<T>> xx;
for (int i = 0; i < b.get(0).size(); i++) {
final int j = i;
if (b.size() > 1) {
xx = product(b.stream().skip(1).collect(Collectors.toList()));
xx = xx.stream().map(x ->
Stream.concat(Stream.of(b.get(0).get(j)), x.stream()).collect(Collectors.toList())
).collect(Collectors.toList());
} else {
xx = Arrays.asList(Arrays.asList(b.get(0).get(i)));
}
result.addAll(xx);
}
return result;
}
}
// OUTPUT
// [[A, 4, 0], [A, 5, 0], [B, 4, 0], [B, 5, 0], [C, 4, 0], [C, 5, 0]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment