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

DaftLeech :
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?

Eran :

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 ()));

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=430530&siteId=1