Skip to content

Instantly share code, notes, and snippets.

Embed
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;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
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();
})
.collect(Collectors.toList());
System.out.println(lengths);
}
private static class Samples
implements Iterable<String> {
private final List<String> samples;
private Samples(List<String> samples) {
this.samples = new ArrayList<>(samples);
}
@Override
public java.util.Iterator<String> iterator() {
return new Iterator();
}
public Stream<String> parallelStream() {
return StreamSupport.stream(this.spliterator(), true);
}
private class Iterator
implements java.util.Iterator<String> {
private int index;
public Iterator() {
this.index = 0;
}
@Override
public boolean hasNext() {
return (this.index < (Samples.this.samples.size() - 1));
}
@Override
public String next() {
final String nextString = Samples.this.samples.get(this.index++);
System.out.println("Requesting " + nextString);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
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.