What is the difference between the map and flatMap methods in Java 8?
What is the difference between the methods Stream.map
and Stream.flatMap
apart from each other?
1 answers
Both map
and flatMap
can be applied to the stream Stream<T>
and both return the stream Stream<R>
. The difference is that the map
operation creates one output value for each input value, whereas the flatMap
operation creates an arbitrary number (zero or more) of values for each input value.
Operation map
(About the work map
in Russian) takes as an argument Function
(for example, lambda), which is called for each value of the input stream(which is <T>
), converts this value to another value, and sends the resulting value to the output stream(which is <R>
).
I.e. map
returns 1 object for each object in the stream, then converts all objects to the final stream.
Operation flatMap
(About the work flatMap
in Russian) takes a function (which converts each value of the input stream to a stream), applies it to each element, and returns a stream with one of the following parameters:, multiple or none of the elements for each element of the incoming stream.
I.e., flatMap
returns a stream for each object in the original stream, and then the resulting streams are combined into the original stream.
Example for map
: there is a one-dimensional array array
with numbers. You need to get an array from the original array, in which 1 is added to each number.
Solution:
array = Arrays.stream(array) //преобразовываем массив в стрим
.map(i -> i+1) //преобразовываем каждый элемент стрима
.toArray(); //преобразовываем стрим в массив
map
to each value, the stream adds 1, then converts all the new values to the final stream.
Example for flatMap
: there is a two-dimensional array
with numbers, you need to get a one-dimensional array with numbers.
Decision:
secondArray = Arrays.stream(array)
.flatMapToInt(i -> Arrays.stream(i)) //преобразовываем Stream<int[]> в Stream
.toArray(); // преобразовываем Stream в int[]
In this example, a stream is created consisting of each element of the original array - that is, a stream of arrays. Then, using i -> Arrays.stream(i)
, we transform each element(which is an array) of the stream into a stream with numbers. After that, flatMap
collects all the resulting streams into one final stream.