Java Flatmap vs Map #
Java 8 map() and flatMap() are two important methods of java.util.stream.Stream interface used for transformation or mapping operations. Both are intermediate operations. The only difference is that map() takes Stream <T>
as input and return Stream <R>
where as flatMap() takes Stream<Stream <T>
as input and return Stream <R>
i.e flatmap() removes extra layer of nesting around input values. Let’s see the differences between Java 8 map() and flatMap() methods in detail.
map() | flatMap() |
---|---|
It processes stream of values. | It processes stream of stream of values. |
It does only mapping. | It performs mapping as well as flattening. |
It’s mapper function produces single value for each input value. | It’s mapper function produces multiple values for each input value. |
It is a One-To-One mapping. | It is a One-To-Many mapping. |
Data Transformation : From Stream<T> to Stream<R> |
Data Transformation : From Stream<Stream<T> to Stream<R> |
Use this method when the mapper function is producing a single value for each input value. | Use this method when the mapper function is producing multiple values for each input value. |