In Java 8 Stream API,
flatMap() method is an intermediate functions for streams, in that, it will produce a final result but used to apply transformations on the elements of a Stream. It is possible to to chain multiple
flatMap() while processing a single stream.
Both
map() and
flatMap() both can be applied to a Stream<T> and return a Stream<R> or transformed elements, but the main difference is that
map() produces one output element for each input element, whereas
flatMap() produces any number (0-n) of output elements for each input element. Put simply, when using a
map(), the resulting stream would have same number or elements as the input stream, where as it can be different in case of a
flatMap(). The following example illustrates the differences the use of
flatMap()