Difference Between map() And flatMap() In Java Stream
In Java, the Stream interface has a map() and flatmap() methods and both have intermediate stream operation and return another stream as method output. Both of the functions map() and flatMap are used for transformation and mapping operations. map() function produces one output for one input value, whereas flatMap() function produces an arbitrary no of values as output (ie zero or more than zero) for each input value.
The Syntax of the map() is represented as:
<R> Stream<R> map(Function<? super T, ? extends R> mapper)
The Syntax of the flatMap() is represented as:-
<R> Stream<R> flatMap(Function<? super T, ? extends Stream<? extends R>> mapper)
Where R is the element type of the new stream. The stream is an interface and T is the type of stream elements and mapper is a stateless function that is applied to each element and the function returns the new stream.
map() can be used where we have to map the elements of a particular collection to a certain function, and then we need to return the stream which contains the updated results.
Example: Multiplying All the elements of the list by 3 and returning the updated list.
flatMap() can be used where we have to flatten or transform out the string, as we cannot flatten our string using map().
Example: Getting the 1st Character of all the String present in a List of Strings and returning the result in form of a stream.
Difference Between map() and flatmap()
map() flatMap() The function passed to map() operation returns a single value for a single input. The function you pass to flatmap() operation returns an arbitrary number of values as the output. One-to-one mapping occurs in map(). One too many mapping occurs in flatMap(). Only perform the mapping. Perform mapping as well as flattening. Produce a stream of value. Produce a stream of stream value. map() is used only for transformation. flatMap() is used both for transformation and mapping.
Below are the Java Programs using map() function:
List of fruit-[Apple, mango, pineapple, kiwi] List generated by map-[5, 5, 9, 4]
Below is the Java Program using flatMap():
List of list-[[1, 2], [3, 4], [5, 6], [7, 8]] List generate by flatMap-[1, 2, 3, 4, 5, 6, 7, 8]
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.