Java Reference
In-Depth Information
List<Integer> dishNameLengths = menu.stream()
.map(Dish::getName)
.map(String::length)
.collect(toList());
5.2.2. Flattening streams
You saw how to return the length for each word in a list using the method map. Let's extend this
idea a bit further: how could you return a list of all the unique characters for a list of words? For
example, given the list of words ["Hello", "World"] you'd like to return the list ["H", "e", "l", "o",
"W", "r", "d"].
You might think that this is easy, that you can just map each word into a list of characters and
then call distinct to filter duplicate characters. A first go could be like this:
words.stream()
.map(word -> word.split(""))
.distinct()
.collect(toList());
The problem with this approach is that the lambda passed to the map method returns a String[]
(an array of String) for each word. So the stream returned by the map method is actually of type
Stream<String[]>. What you really want is Stream<String> to represent a stream of characters.
Figure 5.5 illustrates the problem.
 
Search WWH ::




Custom Search