Skip to content

Instantly share code, notes, and snippets.

@kjkrol
Last active March 1, 2022 11:52
  • Star 5 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
Star You must be signed in to star a gist
Embed
What would you like to do?
Zipping streams using JDK8 with lambda
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);
}
}
@SilviaIenciu
Copy link

Hi,
Can you please license this code of yours?
thanks

@kjkrol
Copy link
Author

kjkrol commented Dec 17, 2020

Hi,
Can you please license this code of yours?
thanks

Feel free to use it :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment