-2

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.

azro
  • 53,056
  • 7
  • 34
  • 70
shiva
  • 2,535
  • 2
  • 18
  • 32
  • 1
    Honestly: what does it matter what the words *specifically* refer to? It is clear what the result actually is: apply the mapping function to the elements and then concat all the resulting sub streams into one big stream. – luk2302 May 24 '21 at 17:32
  • @luk2302 I read some tutorials and blogs and understood how flatMap works. However, I wanted to verify what I understood from those tutorials. For the few examples I could think of, it worked correctly. Also, I wanted to know the gaps in my understanding of the docs because I want to be able to understand these operations from the docs. I don't know any significant advantages of doing that, but it would help to consult docs for trivial things rather than going through tutorials. – shiva May 25 '21 at 05:06

1 Answers1

2

The contents of the mapped stream are the elements in the stream returned by mapper. A regular map(List::stream) would return a stream of streams, as you suggested. The point of flatMap (as indicated in the name) is to "flatten" the result by discarding the inner stream wrappers and combining all the contained elements into one stream.

shmosel
  • 49,289
  • 6
  • 73
  • 138