如何逐个元素添加两个IntStream?

时间:2017-05-22 19:32:40

标签: java java-stream

实施例

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

第一个流提供了无限的[0,0,1,0,0,1...]流,第二个流提供了[0,0,0,0,2,0,0,0,0,2,...]的无限流。

结果流是ri = ai + bi,这意味着我只想从每个流中获取相同位置的元素之和。

这在Java中是否可行?

2 个答案:

答案 0 :(得分:2)

您可以使用Guava的Streams.zip()帮助器:

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

答案 1 :(得分:1)

您可以定义自己的Spliterator,以便稍后从中创建一个流。

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

然后创建一个流并检查结果

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