Skip to content

Instantly share code, notes, and snippets.

@danilomo
Last active November 6, 2018 13:52
Show Gist options
  • Save danilomo/999c9d209e97218fe58c8a9042ca1261 to your computer and use it in GitHub Desktop.
Save danilomo/999c9d209e97218fe58c8a9042ca1261 to your computer and use it in GitHub Desktop.
"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