I have the following collection type:
Map> map;
I would like to create unique combinations of each o
A simpler answer, for a simpler situation where you just want to have the cartesian product of the elements of two collections.
Here's some code which uses flatMap to generate the cartesian product of two short lists:
public static void main(String[] args) {
List aList = Arrays.asList(1,2,3);
List bList = Arrays.asList(4,5,6);
Stream> product = aList.stream().flatMap(a ->
bList.stream().flatMap(b ->
Stream.of(Arrays.asList(a, b)))
);
product.forEach(p -> { System.out.println(p); });
// prints:
// [1, 4]
// [1, 5]
// [1, 6]
// [2, 4]
// [2, 5]
// [2, 6]
// [3, 4]
// [3, 5]
// [3, 6]
}
If you want to add more collections, just nest the streams a litter further:
aList.stream().flatMap(a ->
bList.stream().flatMap(b ->
cList.stream().flatMap(c ->
Stream.of(Arrays.asList(a, b, c))))
);