If you think map()
as an iteration(one level for
loop), flatmap()
is a two-level iteration(like a nested for
loop). (Enter each iterated element foo
, and do foo.getBarList()
and iterate in that barList
again)
map()
: take a stream, do something to every element, collect the single result of every process, output another stream. The definition of "do something function" is implicit. If the processment of any element results in null
, null
is used to compose the final stream. So, the number of elements in the resulting stream will be equal to number of input stream.
flatmap()
: take a stream of elements/streams and a function(explicit definition), apply the function to each element of each stream, and collect all the intermediate resulting stream to be a greater stream("flattening"). If the processment of any element results in null
, empty stream is provided to the final step of "flattening". The number of elements in the resulting stream, is the total of all participating elements in all inputs, if the input is several streams.