转换流<a> into Stream<b> using &#34;B map(A a1,A a2)&#34;

时间:2015-05-18 17:27:12

标签: java java-8 java-stream

I have a Stream<A> of n+1elements and a functions B map(A a1,A a2) which takes two elements of A and returns one element of B. Now I want to get a Stream<B> of nelements such that the i-th element of the new stream is the result of map(a[i],a[i+1]) (here I used the square brackets of course informally). How would you do that?

Bonus: Is there even a more general solution which converts a Stream<A> of n-m+1elements using a function B map(A a1,A a2,...,A am) to a Stream<B> of nelements?

1 个答案:

答案 0 :(得分:4)

你可以使用我的库StreamEx,它具有完全解决你的第一个任务的功能:

Stream<A> src = //...
Stream<B> res = StreamEx.of(src).pairMap(this::map);

在内部,此功能背后有一个自定义spliterator。因此,如果您不想要额外的依赖项,您可以在项目中实现类似的spliterator。

由于许多原因,我没有为奖金任务实施更一般的解决方案。但是protonpack库中有类似的功能。通过这个库,您的任务可以解决为:

Stream<B> res = StreamUtils.windowed(src, 2).map(l -> map(l.get(0), l.get(1)));

但它无法并行化。我的分裂器非常平行。