Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Demo of how sequential iterators behave with parallel streams in Java 8
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class TestIterators {
public static void main(String[] args) {
List<String> strings =
Arrays.asList("ab", "cdef", "g", "hijk", "lmn", "opqr", "stu", "vwx", "yz");
List<Integer> lengths;
lengths = new Samples(strings).parallelStream()
.map((s) -> {
System.out.printf("Thread %s: Processing %s\n", Thread.currentThread().toString(), s);
return s.length();
private static class Samples
implements Iterable<String> {
private final List<String> samples;
private Samples(List<String> samples) {
this.samples = new ArrayList<>(samples);
public java.util.Iterator<String> iterator() {
return new Iterator();
public Stream<String> parallelStream() {
return, true);
private class Iterator
implements java.util.Iterator<String> {
private int index;
public Iterator() {
this.index = 0;
public boolean hasNext() {
return (this.index < (Samples.this.samples.size() - 1));
public String next() {
final String nextString = Samples.this.samples.get(this.index++);
System.out.println("Requesting " + nextString);
try {
} catch (InterruptedException e) {
return nextString;
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.