This question is not about flatMap() in general. I want to understand the documentation of flatMap.
Documentation says:
Returns a stream consisting of the results of replacing each element of this stream with the contents of a mapped stream produced by applying the provided mapping function to each element.
Assume we have the below code:
List<List<Integer>> list = Arrays.asList(Arrays.asList(1,2,3), Arrays.asList(4,5,6));
list.stream()
.flatMap(lst -> lst.stream())
.forEach(val -> System.out.println(val));
As per the docs, "each element of this stream" would mean the lists [1,2,3]
and [4,5,6]
. Mapping function is List::stream
and applying this function on the two lists would give us two stream objects of type - Stream<String>
. Now I am not able to understand how we get the final output as Stream<String>
and not Stream<Stream<String>>
. (I know we would get the latter if we use stream.map()
instead of stream.flatMap()
)
However, if we follow the docs shouldn't we get Stream<Stream<String>>
?
And can someone please explain the meaning of the term mapped stream in the context of this example? What will be the type/value of the mapped stream? What are the "contents of this mapped stream"?
Please help me understand this doc.