2017-05-22 77 views
3

示例;如何添加兩個IntStreams元素?

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中可能嗎?

+1

實現一個'Spliterator'顯然是最好的方法:https://stackoverflow.com/q/30685623/1896169 – Justin

+0

什麼是'創建'? –

+0

@YCF_L。這在問題中已清楚解釋。 –

回答

2

您可以使用番石榴的Streams.zip()幫手:

IntStream sum(IntStream a, IntStream b) { 
    return Streams.zip(a.boxed(), b.boxed(), Integer::sum) 
      .map(Integer::intValue); 
} 
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); 
+1

我會使用'Math.min(a.estimateSize(),b.estimateSize())'作爲估計的大小...... – Holger