使用lambda或Stream API合并流以产生交替序列 [英] merge streams to produce alternating sequence using lambda or Stream API
问题描述
我有一些代码可以按预期返回Stream,但是也许可以用某种类型的lambda或stream()操作代替它,而不用在while
循环中耗尽迭代器?
I have some code which returns a Stream as intended, but maybe it can be replaced with some type of lambda or stream() operation instead of exhausting the iterators in a while
loop?
这只是一种方法,它交替使用流first
和second
中的元素,并在其中一个元素用完时停止.
It is just a method that alternates elements from the streams first
and second
and stops when one of them runs out of elements.
public static <T>Stream<T> alternatingSequence(Stream<T> first, Stream<T> second){
Iterator<T> iteratorFirst = first.iterator();
Iterator<T> iteratorSecond = second.iterator();
Stream<T> resultStream = Stream.empty();
while (iteratorFirst.hasNext() && iteratorSecond.hasNext()){
resultStream = Stream.concat(resultStream, Stream.of(iteratorFirst.next(), iteratorSecond.next()));
}
return resultStream;
}
}
推荐答案
Using Guava's Streams.zip you can combine the two streams into a stream of two-element streams, which you may then simply flatten to produce an alternating sequence:
return Streams.zip(first, second, (arg1, arg2) -> Stream.of(arg1, arg2))
.flatMap(Function.identity());
一个警告是,生成的流无法有效拆分(请参阅链接的文档).这可能会损害并行性能.
One caveat is that the resulting stream is not efficiently splittable (see linked doc). This may harm parallel performance.
注意:
如果您无权访问番石榴,则可以实现自己的zip(a, b, bifunc)
,如此处所示.
If you don't have access to Guava then you can implement your own zip(a, b, bifunc)
as shown here.
这篇关于使用lambda或Stream API合并流以产生交替序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!