Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
"Zip with index" in Java 8 stream API
import java.util.Iterator;
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) -> {
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, 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;
public Pair<K, V> next() {
return new Pair<>(,;
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.