Java Reference
In-Depth Information
Step 1: Defining the Collector class signature
Let's start with the class signature, remembering that the Collector interface is defined as
public interface Collector<T, A, R>
where T, A, and R are respectively the type of the elements in the stream, the type of the object
used to accumulate partial results, and the type of the final result of the collect operation. In this
case, you want to collect streams of Integers while both the accumulator and the result types are
Map<Boolean, List<Integer>> (the same Map you obtained as a result of the former
partitioning operation in listing 6.6 ) , having as keys true and false and as values respectively the
Lists of prime and nonprime numbers:
Step 2: Implementing the reduction process
Next, you need to implement the five methods declared in the Collector interface. The supplier
method has to return a function that when invoked creates the accumulator:
public Supplier<Map<Boolean, List<Integer>>> supplier() {
return () -> new HashMap<Boolean, List<Integer>>() {{
put(true, new ArrayList<Integer>());
put(false, new ArrayList<Integer>());
}};
}
Here you're not only creating the Map that you'll use as the accumulator, but you're also
initializing it with two empty lists under the true and false keys. This is where you'll add
respectively the prime and nonprime numbers during the collection process. The most
important method of your collector is the accumulator method, because it contains the logic
defining how the elements of the stream have to be collected. In this case, it's also the key to
implementing the optimization we described previously. At any given iteration you can now
access the partial result of the collection process, which is the accumulator containing the prime
numbers found so far:
 
Search WWH ::




Custom Search