Java Reference
In-Depth Information
Java 8 introduces a new type called Spliterator. A spliterator is like an iterator, in that its job is to produce
a sequence of elements. Just like an iterator, the sequence of elements could be finite or infinite, but it's
usually finite. The big difference between an iterator and a spliterator is that the spliterator has the ability
to “split.” The concept of splitting a spliterator is that you break one spliterator into two, with some portion
of the elements returned by the original spliterator and some portion of the elements returned by a new
Assume that you had a spliterator of English letters, “A” to “Z.” You could draw “A,” “B,” and “C” from
your spliterator, and then split it. At this point, the spliterator might start to provide only the remaining
consonants (“d,” “f,” “g,” “h,” “j”…) and return a new spliterator for the remaining vowels (“e,” “i,” “u”…).
These two spliterators would then be entirely independent, and could be executed in any order without
any interdependency. The rule is just that no element should be lost in the split, and no element should be
duplicated by the split spliterators.
In Java 8, spliterators provide the elements that will become the stream elements. All the various stream
operations are really operations on spliterators and the elements that come out of them. You generate a stream
from a spliterator by passing in the spliterator instance into the, boolean)
method. The second argument specifies whether the resulting stream is “parallel” or “sequential”: a parallel
stream is allowed to operate on elements in any order and operate on multiple elements at the same time;
a sequential stream will always execute within the caller's thread, and will conclude processing an earlier
element before processing the next. If a previous element might alter the interpretation of a later element,
then you have to create a sequential stream. If the elements are capable of being processed distinctly,
then you should create a parallel stream. By default, streams in Java are sequential, because that is the safe
answer. If it is at all possible, however, you should use parallel streams by calling stream.parallel() and
using the returned stream. A concrete example of these different modes is given in Listing 5-8.
Listing 5-8. Results of Running a Stream in Parallel vs. in Sequence
public class Listing8 {
public static void main(String[] args) throws Exception {
IntStream stream;
// Sequential stream—commonly default mode
stream = IntStream.range(1, Integer.MAX_VALUE);
stream.sequential().mapToObj(i -> {
System.out.println("Mapping " + i + " to string");
return Integer.toString(i);
/* Example output sampling
Mapping 34438924 to string
Mapping 34438925 to string
Mapping 34438926 to string
Mapping 34438927 to string
Mapping 34438928 to string
Search WWH ::

Custom Search