What you are asking seems to be cartesian product of N sets (Set1 x Set2 x ... x SetN
).
Unfortunately there is no standard method in Java which would allow us to build one easily, but with little help of Guava and its Sets.cartesianProduct
method this task seems quite easy.
Only condition is that we need to provide as its argument List<Set<..>>
.
Because of that this answer is based on assumption that each int[] is can be treated as set, which means that its values must be unique. Actually to be more precise if index 0
will be {1,2,1}
or {1,2,2}
it will be processed as set {1,2}
.
Here is example with List<Set<Integer>>
with your current data
(toList
is statically imported Collections.toList()
method, similarly toSet
) :
//part 0: preparing data
List<Set<Integer>> sets = new ArrayList<>(
Arrays.asList(
new HashSet<>(Arrays.asList(1, 2)),
new HashSet<>(Arrays.asList(1, 3, 5)),
new HashSet<>(Arrays.asList(2))
)
);
sets.forEach(System.out::println);
System.out.println("-----------------");
//part 1: calculating cartesian products
Set<List<Integer>> cartesianProducts = Sets.cartesianProduct(sets);
System.out.println(cartesianProducts);
System.out.println("-----------------");
//part 2
List<List<Integer>> noDuplicatesInProducts = cartesianProducts
.stream()//iterate over each cartesian product
.map(product -> product.stream()
.distinct()//remove duplicate values
.collect(toList())//store updated product as list
).collect(toList());//store all products as list
System.out.println(noDuplicatesInProducts);
Output:
[1, 2]
[1, 3, 5]
[2]
-----------------
[[1, 1, 2], [1, 3, 2], [1, 5, 2], [2, 1, 2], [2, 3, 2], [2, 5, 2]]
-----------------
[[1, 2], [1, 3, 2], [1, 5, 2], [2, 1], [2, 3], [2, 5]]
If you are looking for a way to convert List<int[]>
to List<Set<Integer>>
here is one example:
private static List<Set<Integer>> convert(List<int[]> list) {
return list
.stream()
.map(arr ->
IntStream.of(arr)
.mapToObj(Integer::valueOf)// same as .boxed()
.collect(toSet())
).collect(toList());
}