Stream a = Stream.of(\"one\", \"three\", \"five\");
Stream b = Stream.of(\"two\", \"four\", \"six\");
What do I need
I’d use something like this:
public static Stream 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(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);
}
It retains the characteristics of the input streams as far as possible, which allows certain optimizations (e.g. for count()
and toArray()
). Further, it adds the ORDERED
even when the input streams might be unordered, to reflect the interleaving.
When one stream has more elements than the other, the remaining elements will appear at the end.