Java Reference
In-Depth Information
In this method, you invoke the isPrime method, passing to it (together with the number for
which you want to test whether it's prime or not) the list of the prime numbers found so far
(these are the values indexed by the true key in the accumulating Map). The result of this
invocation is then used as key to get the list of either the prime or nonprime numbers so you can
add the new candidate to the right list.
Step 3: Making the collector work in parallel (if possible)
The next method has to combine two partial accumulators in the case of a parallel collection
process, so in this case it just has to merge the two Maps by adding all the numbers in the prime
and nonprime lists of the second Map to the corresponding lists in the first Map:
public BinaryOperator<Map<Boolean, List<Integer>>> combiner() {
return (Map<Boolean, List<Integer>> map1,
Map<Boolean, List<Integer>> map2) -> {
map1.get(true).addAll(map2.get(true));
map1.get(false).addAll(map2.get(false));
return map1;
};
}
Note that in reality this collector can't be used in parallel, because the algorithm is inherently
sequential. This means the combiner method won't ever be invoked, and you could leave its
implementation empty (or better, throw an UnsupportedOperation-Exception). We decided to
implement it anyway only for completeness.
Step 4: The finisher method and the collector's characteristic method
The implementation of the last two methods is quite straightforward: as we said, the
accumulator coincides with the collector's result so it won't need any further transformation,
and the finisher method returns the identity function:
public Function<Map<Boolean, List<Integer>>,
 
Search WWH ::




Custom Search