I am working with Streams(Java 8) and when I use the method .stream()
it is not clear to me the difference between .map
and .flatMap
. What differences are there between these methods?
I am working with Streams(Java 8) and when I use the method .stream()
it is not clear to me the difference between .map
and .flatMap
. What differences are there between these methods?
The difference is that it
map()
returns the same number of elements as the input Stream since it is simply a projection of the input elements. That is, each input element is transformed into an output element.On the other hand
.flatMap()
, it projects a list of elements from each original element and concatenates them into a single stream .For example:
map()
flatMap()
Well, the difference is that .map produces an output value for each input value and .flatmap produces from zero to n output values for each input value, more or less as follows:
map::Stream T (I -> O) flapmap::Stream T (I -> Stream O)
I enclose an example code: