Java Reference
In-Depth Information
List<Dish> dishes = menuStream.collect(toList());
formulation is that toList is a factory, whereas you have to use new to instantiate your
ToListCollector.
Performing a custom collect without creating a Collector
implementation
In the case of an IDENTITY_FINISH collection operation, there's a further possibility of
obtaining the same result without developing a completely new implementation of the Collector
interface. Stream has an overloaded collect method accepting the three other
functions—supplier, accumulator, and combiner—having exactly the same semantics as the ones
returned by the corresponding methods of the Collector interface. So, for instance, it's possible
to collect in a List all the items in a stream of dishes as follows:
We believe that this second form, even if more compact and concise than the former one, is
rather less readable. Also, developing an implementation of your custom collector in a proper
class promotes its reuse and helps avoid code duplication. It's also worth noting that you're not
allowed to pass any Characteristics to this second collect method, so it always behaves as an
IDENTITY_FINISH and CONCURRENT but not UNORDERED collector.
In the next section, you'll take your new knowledge of implementing collectors to the next level.
You'll develop your own custom collector for a more complex but hopefully more specific and
compelling use case.
6.6. Developing your own collector for better performance
In section 6.4 , where we discussed partitioning, you created a collector, using one of the many
convenient factory methods provided by the Collectors class, which divides the first n natural
numbers into primes and nonprimes, as shown in the following listing.
 
Search WWH ::




Custom Search