Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
"Zip with index" in Java 8 stream API
import java.util.Iterator;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
import javafx.util.Pair;
public class ZipWithIndex {
public static void main(String[] args) {
Stream<String> s = Stream.of("One", "Two", "Three", "Four", "Five");
Stream<Integer> indexes = Stream.iterate(1, i -> i + 1);
zip( s, indexes ).forEach((t) -> {
System.out.println(t);
});
}
static <T, V> Stream<Pair<T,V>> zip(Stream<T> first, Stream<V> second ){
Iterable<Pair<T,V>> iterable = () -> new ZippedIterator<>(first.iterator(), second.iterator());
return StreamSupport.stream(iterable.spliterator(), false);
}
static class ZippedIterator<K, V> implements Iterator<Pair<K, V>> {
public final Iterator<K> first;
public final Iterator<V> second;
public ZippedIterator(Iterator<K> first, Iterator<V> second) {
this.first = first;
this.second = second;
}
@Override
public Pair<K, V> next() {
return new Pair<>(first.next(), second.next());
}
@Override
public boolean hasNext() {
return first.hasNext() && second.hasNext();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.