In order to understand the flatMap() method, you first need to understand the map() function of Java 8. The map() function is declared in the java.util.stream.Stream class and uses to transform one Stream into another e.g. a stream of integer numbers into another stream of ints where each element is the square of the corresponding element in source stream. In the map() function, a function is applied to each element of Stream and return values are inserted into a new Stream. The key point to note here is that the function used by map() operation returns a single value. Now, if the map operation uses a function which instead of returning a single value returns a Stream of values e.g. prime factors of the number then you have a Stream of Stream of integers. The flatMap() method is used to flatten that stream into a Stream of integers. For example, suppose, you have a list of numbers e.g. [21, 23, 42] and we use getPrimeFactors() method along with the map() operation to transform this stream. The result would be [[3,7],[23],[2,3,7]]. If you want to flat this stream of a stream into a stream of values, you can use the flatMap() which will return [3,7,2,3,2,3,7].
Read more »