Java Reference
In-Depth Information
Figure 10.3. A two-level optional
So how can we solve this problem? Again, we can look at a pattern you've used previously with
streams: the flatMap method. With streams, the flatMap method takes a function as an
argument, which returns another stream. This function is applied to each element of a stream,
which would result in a stream of streams. But flatMap has the effect of replacing each
generated stream by the contents of that stream. In other words, all the separate streams that
are generated by the function get amalgamated or flattened into a single stream. What you want
here is something similar, but you want to flatten a two-level optional into one.
Like figure 10.2 for the map method, figure 10.4 illustrates the similarities between the flatMap
methods of the Stream and Optional classes.
Figure 10.4. Comparing the flatMap methods of Stream and Optional
Here the function passed to the stream's flatMap method transforms each square into another
stream containing two triangles. The result of a simple map would then be a stream containing
three other streams, each of them having two triangles, but the flatMap method flattens this
two-level stream into a single stream containing six triangles in total. In the same way, the
 
Search WWH ::




Custom Search