How to interleave (merge) two Java 8 Streams?

前端 未结 6 1835
有刺的猬
有刺的猬 2020-12-16 16:43
 Stream a = Stream.of(\"one\", \"three\", \"five\");
 Stream b = Stream.of(\"two\", \"four\", \"six\");

What do I need

6条回答
  •  粉色の甜心
    2020-12-16 17:41

    I’d use something like this:

    public static  Stream interleave(Stream a, Stream b) {
        Spliterator 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 sp1 = spA, sp2 = spB;
    
            @Override
            public boolean tryAdvance(Consumer action) {
                Spliterator 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.

提交回复
热议问题