int[] ar1 = {1,2,3};
int[] ar2 = {1,2,3};
Output:
{2,3,4,3,4,5,4,5,6}
I tried something like this:
IntStream.range(0,ar1.length).map(x -> IntStream.range(0,ar2.length).map(y -> ar1[y]+ar2[x]));
but this does not work:
Type mismatch: cannot convert from
IntStream
toint
.
How can I sum every value of ar1
with every value of ar2
in Java 8 using streams?
You should use flatMap
, since map
of IntStream
is expected to map each int
element of the original IntStream
to an int
, not to an IntStream
.
System.out.println(Arrays.toString (
IntStream.range(0,ar1.length)
.flatMap(x -> IntStream.range(0,ar2.length).map(y -> ar1[x]+ar2[y]))
.toArray ()));
Output:
[2, 3, 4, 3, 4, 5, 4, 5, 6]
As an alternative to creating an IntStream
of the indices of the array, you can create an IntStream
of the elements of the array:
System.out.println(Arrays.toString (
Arrays.stream(ar1)
.flatMap(x -> Arrays.stream(ar2).map(y -> x + y))
.toArray ()));
For each i
th element, you can create a IntStream
of sums i + j
of this element and a j
th element of another array:
IntStream.of(ar1).flatMap(i -> IntStream.of(ar2).map(j -> i + j)).toArray();
I would not recommend using streams of indexes (IntStream.range(0,ar1.length)
) where they can be replaced with streams of values themselves (IntStream.of(ar1)
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With