Last active
March 1, 2022 11:52
-
-
Save kjkrol/51a5a7612f0411849c62 to your computer and use it in GitHub Desktop.
Zipping streams using JDK8 with lambda
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Iterator; | |
import java.util.function.BiFunction; | |
import java.util.stream.Stream; | |
import java.util.stream.StreamSupport; | |
/** | |
* Zipping streams into parallel or sequential stream using JDK8 with lambda | |
* | |
* @author Karol Krol | |
*/ | |
public final class StreamZip { | |
private StreamZip() { | |
} | |
public static <A, B, C> Stream<C> zip(Stream<A> streamA, Stream<B> streamB, BiFunction<A, B, C> zipper) { | |
final Iterator<A> iteratorA = streamA.iterator(); | |
final Iterator<B> iteratorB = streamB.iterator(); | |
final Iterator<C> iteratorC = new Iterator<C>() { | |
@Override | |
public boolean hasNext() { | |
return iteratorA.hasNext() && iteratorB.hasNext(); | |
} | |
@Override | |
public C next() { | |
return zipper.apply(iteratorA.next(), iteratorB.next()); | |
} | |
}; | |
final boolean parallel = streamA.isParallel() || streamB.isParallel(); | |
return iteratorToFiniteStream(iteratorC, parallel); | |
} | |
public static <T> Stream<T> iteratorToFiniteStream(Iterator<T> iterator, boolean parallel) { | |
final Iterable<T> iterable = () -> iterator; | |
return StreamSupport.stream(iterable.spliterator(), parallel); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Feel free to use it :)