What is Java flatMap?
The Java flatMap() returns a stream that contains the contents of a mapped stream. It is created by applying the mapping function to each element of the original stream. An intermediary operation is stream flatMap(Function mapper). These processes are always time-taking. A Stream instance as the input will be used for intermediate operations.And, it will return a Stream instance as output once they have completed processing.

The syntax to use Java flatMap() is given below:
<R> Stream<R> flatMap(Function<? super T, ? extends Stream<? extends R>> mapper)
In the above code R is the new stream's element type. An interface is a stream, and the type of stream element is T. A stateless function called mapper is applied to each element and returns a new stream.
Also read, Duck Number in Java and Hashcode Method in Java
How does Java flatMap() work?
The process of flattening involves merging multiple lists of lists into a single list that contains every element from all the original lists.
As was already mentioned in the post, Java flatMap() combines the map and flat operations, applying the map function first and then flattening the outcome. Following are the examples for how flattening happens:
-
Consider the following lists of lists of integers:
Before Flattening: [[6, 0, 5, 8], [0, 41, 7, 1], [4, 39], [72, 16, 9, 0, 7], [2]]
After Flattening: [6, 0, 5, 8, 0, 41, 7, 1, 4, 39, 72, 16, 9, 0, 7, 2]
-
Consider the following lists of lists of charcters:
Before Flatenning: [ ["C", "O", "D"], ["I", "N", "G"], ["N", "I", "N"], ["J", "A"], ["S"] ]
After Flatenning: ["C", "O", "D", "I", "N", "G", "N", "I", "N", "J", "A", "S"]
In a nutshell, we can say that after flattening, the Stream of <<Data Type>> is returned if there was a Stream of List of <<Data Type>> before flattening.
Also see, Swap Function in Java