Stream<String> a = Stream.of("one", "three", "five");
Stream<String> b = Stream.of("two", "four", "six");
我需要做什么才能得到下面的输出?
// one
// two
// three
// four
// five
// six
我研究了concat
,但正如javadoc所解释的,它只是一个接一个地附加,它不会交错/散布。
Stream<String> out = Stream.concat(a, b);
out.forEach(System.out::println);
Creates a lazily concatenated stream whose elements are all the elements of the first stream followed by all the elements of the second stream.
错误给出
// one
// three
// five
// two
// four
// six
如果我收集它们并迭代就可以做到,但希望有更多 Java8-y、Streamy 的东西:-)
注意
我不想压缩流
“zip” operation will take an element from each collection and combine them.
zip 操作的结果将是这样的:(不需要)
// onetwo
// threefour
// fivesix
最佳答案
我会使用这样的东西:
public static <T> Stream<T> interleave(Stream<? extends T> a, Stream<? extends T> b) {
Spliterator<? extends T> spA = a.spliterator(), spB = b.spliterator();
long s = spA.estimateSize() + spB.estimateSize();
if(s < 0) s = Long.MAX_VALUE;
int ch = spA.characteristics() & spB.characteristics()
& (Spliterator.NONNULL|Spliterator.SIZED);
ch |= Spliterator.ORDERED;
return StreamSupport.stream(new Spliterators.AbstractSpliterator<T>(s, ch) {
Spliterator<? extends T> sp1 = spA, sp2 = spB;
@Override
public boolean tryAdvance(Consumer<? super T> action) {
Spliterator<? extends T> sp = sp1;
if(sp.tryAdvance(action)) {
sp1 = sp2;
sp2 = sp;
return true;
}
return sp2.tryAdvance(action);
}
}, false);
}
它尽可能保留输入流的特征,从而允许进行某些优化(例如对于 count()
和 toArray()
)。此外,即使输入流可能无序,它也会添加 ORDERED
以反射(reflect)交错。
当一个流的元素多于另一个流时,剩余的元素将出现在末尾。
关于java - 如何交错(合并)两个 Java 8 Stream?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53307682/