Zipping Steams...

Brent Walker brenthwalker at
Sun Jan 12 15:58:39 PST 2014

Suppose I wanted to implement Haskell's or ML's zip() function for streams
(assume I have my own Pair<U, T> class).  One easily comes up with the
following function:

public static <T, U> Stream<Pair<T, U>> zip(final Stream<T> ts, final
Stream<U> us) {
    final T[] tsVec = (T[]) ts.toArray();

    final U[] usVec = (U[]) us.toArray();

    final int siz = Math.min(tsVec.length, usVec.length);

    return IntStream.range(0, siz).mapToObj(i -> Pair.create(tsVec[i],

This works fine for my needs but as a general routine this function has
issues.  First, it doesn't work at all for infinite streams, and second,
there are those intermediate data structures it builds (tsVec, and usVec)
in order to function which are wasteful (at least they look wasteful).

Is there a better way to implement zip that avoids the above two problems?

Thanks for any suggestions/ideas etc.


More information about the lambda-dev mailing list