How to add IntStreams item by item?

Example

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

      

The first stream gives an endless stream [0,0,1,0,0,1...]

and the second gives an endless stream [0,0,0,0,2,0,0,0,0,2,...]

.

The resulting stream is ri = ai + bi, which means I just want to take the sum of the items in one position from each stream.

Is this possible in Java?

+3


source to share


2 answers


You can use Guava Streams.zip()

helper:



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

      

+2


source


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

      

+1


source







All Articles