Here is a solution using IntStream
with two int
arrays as the source instead of List<Integer>
. I wanted to see if it was possible to solve this problem without boxing every int
as an Integer
.
int[] one = new int[]{1, 2, 3};
int[] two = new int[]{3, 4};
List<IntIntPair> list = new ArrayList<>();
IntStream.of(one).forEach(i ->
IntStream.of(two).mapToObj(j -> PrimitiveTuples.pair(i, j)).forEach(list::add));
System.out.println(list);
// [1:3, 1:4, 2:3, 2:4, 3:3, 3:4]
Unfortunately, I couldn't use flatMap
on IntStream
as it returns an IntStream
. There is no flatMapToObj
currently on IntStream
, which is what would be needed here. So I used forEach
instead.
The IntIntPair
and PrimitiveTuples
classes I used from Eclipse Collections, as they made it simpler to just output the list as a string. You could use int[]
as you have in your solution. The code would look as follows.
List<int[]> list = new ArrayList<>();
IntStream.of(one).forEach(i ->
IntStream.of(two).mapToObj(j -> new int[]{i, j}).forEach(list::add));
In the 8.1 release of Eclipse Collections (to be released mid-March), there is now a flatCollect
method on all primitive containers in the library which can be used to solve this problem. This essentially does what a flatMapToObj
method on IntStream
should do.
IntList a = IntLists.mutable.with(1, 2, 3);
IntList b = IntLists.mutable.with(3, 4);
List<IntIntPair> result =
a.flatCollect(
i -> b.collect(j -> PrimitiveTuples.pair(i, j)),
Lists.mutable.empty());
System.out.println(result);
// [1:3, 1:4, 2:3, 2:4, 3:3, 3:4]
Update:
As pointed out in the comments by Boris the Spider, the forEach
solution would not be thread-safe and would break if the IntStream
was parallel
. The following solution should work in serial or parallel. I'm glad this was pointed out, because I hadn't thought to do a mapToObj
on the IntStream
and then followed by a flatMap
.
int[] one = new int[]{1, 2, 3};
int[] two = new int[]{3, 4};
List<int[]> list = IntStream.of(one).parallel()
.mapToObj(i -> IntStream.of(two).mapToObj(j -> new int[]{i, j}))
.flatMap(e -> e)
.collect(Collectors.toList());
list.stream().map(e -> "{" + e[0] + "," + e[1] + "}").forEach(System.out::println);
Note: I am a committer for Eclipse Collections.