-
-
Save brake/5bf7b0309905a373b3446379e3547c7a to your computer and use it in GitHub Desktop.
Zipping streams using JDK8 with lambda
This file contains hidden or 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