Java Reference
In-Depth Information
The difference between the imperative and functional versions of this example is even more
pronounced if you perform multilevel groupings: in this case the imperative code quickly
becomes harder to read, maintain, and modify due to the number of deeply nested loops and
conditions required. In comparison, the functional-style version, as you'll discover in section 6.3 ,
can be easily enhanced with an additional collector.
6.1.1. Collectors as advanced reductions
This last observation brings up another typical benefit of a well-designed functional API: its
higher degree of composability and reusability. Collectors are extremely useful because they
provide a concise yet flexible way to define the criteria that collect uses to produce the resulting
collection. More specifically, invoking the collect method on a stream triggers a reduction
operation (parameterized by a Collector) on the elements of the stream itself. This reduction
operation , illustrated in figure 6.1 , internally does for you what you had to code imperatively in
listing 6.1 . It traverses each element of the stream and lets the Collector process them.
Figure 6.1. The reduction process grouping the transactions by
currency
Typically, the Collector applies a transforming function to the element (quite often this is the
identity transformation, which has no effect, for example, as in toList), and accumulates the
 
Search WWH ::




Custom Search