简体   繁体   中英

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?

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

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM