Last active
November 6, 2018 13:52
"Zip with index" in Java 8 stream API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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