DaftLeech
DaftLeech

Reputation: 200

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?

Upvotes: 16

Views: 3934

Answers (3)

Andrew
Andrew

Reputation: 49606

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)).

Upvotes: 8

Eran
Eran

Reputation: 393841

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

Upvotes: 15

holi-java
holi-java

Reputation: 30686

Beside that of the IntStream#flatMap, you can use the Arrays#stream(int[]) to create an IntStream. for example:

int[] sum = Arrays.stream(ar1)
                  .flatMap(left -> Arrays.stream(ar2).map(right -> left + right))
                  .toArray();

System.out.println(Arrays.toString(sum));
//                        ^--- [2, 3, 4, 3, 4, 5, 4, 5, 6]

Upvotes: 7

Related Questions