Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java 8 sum all values of two int arrays with each other

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 to int.

How can I sum every value of ar1 with every value of ar2 in Java 8 using streams?

like image 395
DaftLeech Avatar asked Aug 14 '17 09:08

DaftLeech


2 Answers

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 ()));
like image 149
Eran Avatar answered Oct 21 '22 13:10

Eran


For each ith element, you can create a IntStream of sums i + j of this element and a jth 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)).

like image 39
Andrew Tobilko Avatar answered Oct 21 '22 12:10

Andrew Tobilko