What is the difference Stream.map and Stream.flatMap methods?
- 2association: stackoverflow.com/questions/26684562/… - Anton Sorokin
1 answer
Both map and flatMap can be applied to Stream<T> and both return 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.
The map operation ( About the map operation in Russian ) takes the Function (for example, lambda) as an argument, 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 <R> ).
Those. map for each object in the stream returns 1 object, then converts all objects into the final stream.
The flatMap operation ( About flatMap in Russian ) takes a function (which converts each value of the input stream into a stream), applies it to each element, and returns a stream with one, several or none of the elements for each element of the incoming stream at the output.
That is, flatMap returns the flatMap for each object in the original stream, and then the resulting streams are merged into the original stream.
Example for map : there is a one-dimensional array with numbers. It is necessary to obtain an array from the original array, in which 1 is added to each number.
Decision:
array = Arrays.stream(array) //преобразовываем массив в стрим .map(i -> i+1) //преобразовываем каждый элемент стрима .toArray(); //преобразовываем стрим в массив map adds 1 to each value of the stream, then converts all 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 — i.e. stream from arrays. Then, using i -> Arrays.stream(i) transform each element (which is an array) of a stream into a stream with numbers. After that, flatMap collects all the resulting stream into one final stream.