Java Reference
In-Depth Information
Listing 7.3. The Spliterator interface
public interface Spliterator<T> {
boolean tryAdvance(Consumer<? super T> action);
Spliterator<T> trySplit();
long estimateSize();
int characteristics();
}
As usual, T is the type of the elements traversed by the Spliterator. The tryAdvance method
behaves in a way similar to a normal Iterator in the sense that it's used to sequentially consume
the elements of the Spliterator one by one, returning true if there are still other elements to be
traversed. But the trySplit method is more specific to the Spliterator interface because it's used
to partition off some of its elements to a second Spliterator (the one returned by the method),
allowing the two to be processed in parallel. A Spliterator may also provide an estimation of the
number of the elements remaining to be traversed via its estimateSize method, because even an
inaccurate but quick-to-compute value can be useful to split the structure more or less evenly.
It's important to understand how this splitting process is performed internally in order to take
control of it when required. Therefore, we analyze it in more detail in the next section.
7.3.1. The splitting process
The algorithm that splits a Stream into multiple parts is a recursive process and proceeds as
shown in figure 7.6 . In the first step trySplit is invoked on the first Spliterator and generates a
second one. Then in step 2 it's called again on these two Spliterators, which results in a total of
four. The framework keeps invoking the method trySplit on a Spliterator until it returns null to
signal that the data structure that it's processing is no longer divisible, as shown in step 3.
Finally, this recursive splitting process terminates in step 4 when all Spliterators have returned
null to a trySplit invocation.
 
Search WWH ::




Custom Search