KevinS
KevinS

Reputation: 7875

How to interleave Java 8 Stream? Like Collectors.joining() but for things other than Strings

In Java 8, how do I do something like this ...

public String join(Stream<String> strings, String string) {
    return strings.collect(Collectors.joining(string));
}

but for Runnables rather than Strings.

public void join(Stream<Runnable> runnables, Runnable runnable) {

}

In other words, I would like to invoke runnable after each element in the runnables stream except the last.

Upvotes: 3

Views: 577

Answers (2)

castletheperson
castletheperson

Reputation: 33466

First use flatMap to insert the interleaving runnable before every element in the stream, then remove the first element from the stream using skip. Then run all of them in order.

public void join(Stream<Runnable> runnables, Runnable runnable) {
    runnables
        .flatMap(r -> Stream.of(runnable, r))
        .skip(1)
        .forEachOrdered(Runnable::run);
}

Upvotes: 6

Louis Wasserman
Louis Wasserman

Reputation: 198033

runnables
    .reduce((r1, r2) -> () -> { 
         r1.run(); 
         runnable.run();
         r2.run(); 
    })
    .orElse(() -> {})
    .run();

Upvotes: 6

Related Questions