Created
October 12, 2018 15:21
-
-
Save GuyPaddock/56541c18f9da9c5561d432d4ec2957b1 to your computer and use it in GitHub Desktop.
Demo of how sequential iterators behave with parallel streams in Java 8
This file contains hidden or 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.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