0

so I have

Stream<Integer> stream1 = Stream.of(1, 2, 3, 4, 5);
Stream<Integer> stream2 = Stream.of(6, 7, 8, 9, 10);

I want to make stream3 which is the sum of the elements of stream1 and stream2, in other words, 7, 9, 11, 13, 15.

How would I go about doing this with stream operations?

Stefan Zobel
  • 3,182
  • 7
  • 28
  • 38
Taking1n1
  • 145
  • 1
  • 7

3 Answers3

2

Since streams aren’t well suited for this I suggest you collect the elements first, then do the pairwise adding in a new stream:

    IntStream stream1 = IntStream.of(1, 2, 3, 4, 5);
    IntStream stream2 = IntStream.of(6, 7, 8, 9, 10);

    int[] arr1 = stream1.toArray();
    int[] arr2 = stream2.toArray();

    IntStream sumStream = IntStream.range(0, arr1.length)
            .map(index -> arr1[index] + arr2[index]);

    sumStream.forEach(System.out::println);
7
9
11
13
15

You want to check your assumption that there are the same number of elements in both streams, of course, and react adequately if not, may throw an exception. I’ll leave that to you.

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
2

You are looking for the zip operation.

Here is how you can accomplish your task using Google Guava's Streams#zip:

Stream<Integer> stream1 = Stream.of(1, 2, 3, 4, 5);
Stream<Integer> stream2 = Stream.of(6, 7, 8, 9, 10);

Streams.zip(stream1, stream2, Integer::sum)
    .forEach(System.out::println);

The output:

7
9
11
13
15

See also:

Denis Zavedeev
  • 7,627
  • 4
  • 32
  • 53
1

There is the same zip method as @caco3 mentioned, but from StreamEx library, that expand standart stream api:

List<Integer> zip = StreamEx
    .zip(stream1.collect(toList()), stream2.collect(toList()), Integer::sum)
    .collect(toList());

System.out.println(zip);

StreamEx.zip

Ruslan
  • 6,090
  • 1
  • 21
  • 36