rogergl
rogergl

Reputation: 3781

How can I add two IntStreams element by element?

Example;

IntStream a = create(3, 1);  // => [0,0,1]
IntStream b = create(5, 2);  // => [0,0,0,0,2]

The first stream gives an infinite stream of [0,0,1,0,0,1...] and the second an infinite stream of [0,0,0,0,2,0,0,0,0,2,...].

The result stream is ri = ai + bi meaning that I just want to take the sum of the elements at the same position from each stream.

Is this possible in Java ?

Upvotes: 3

Views: 335

Answers (2)

Dmitry P.
Dmitry P.

Reputation: 834

You can define your own Spliterator to create a stream from it later.

import java.util.Comparator;
import java.util.Spliterators;
import java.util.function.IntConsumer;

public class SumSpliterator extends Spliterators.AbstractIntSpliterator {
    private OfInt aSplit;
    private OfInt bSplit;

    SumSpliterator(OfInt a, OfInt b) {
        super(Math.min(a.estimateSize(), b.estimateSize()), Spliterator.ORDERED);
        aSplit = a;
        bSplit = b;
    }

    @Override
    public boolean tryAdvance(IntConsumer action) {
        SummingConsumer consumer = new SummingConsumer();
        if (aSplit.tryAdvance(consumer) && bSplit.tryAdvance(consumer)) {
            action.accept(consumer.result);
            return true;
        }
        return false;
    }

    static class SummingConsumer implements IntConsumer {
        int result;
        @Override
        public void accept(int value) {
            result += value;
        }
    }
}

Then create a stream and check the results

IntStream a = //create stream a
IntStream b = //create stream b
SumSpliterator spliterator = new SumSpliterator(a.spliterator(), b.spliterator());
Stream<Integer> stream = StreamSupport.stream(spliterator, false);
stream.limit(20).forEach(System.out::println);

Upvotes: 1

shmosel
shmosel

Reputation: 50726

You can use Guava's Streams.zip() helper:

IntStream sum(IntStream a, IntStream b) {
    return Streams.zip(a.boxed(), b.boxed(), Integer::sum)
            .map(Integer::intValue);
}

Upvotes: 2

Related Questions