flatMap vs map in Java Explained

In Java, both map and flatMap are methods in the Stream interface that are used to manipulate and transform elements in a stream. The difference between them is as follows:

  1. The map method: The map method is used to apply a function to each element in the stream and wrap the result into a new stream. This means that each element in the original stream will be mapped to a new element, forming a new stream. For example, to square each element in a stream of integers, you can use the map method: stream.map(x -> x * x).
  2. The flatMap method is also used to apply a function to each element in a stream and convert the results into a new stream. However, unlike map, the flatMap method flattens the new stream of each element, merging all the elements of the new streams into a single new stream. For example, if we have a stream of strings where each string contains multiple words, and we want to extract each word and convert it into a separate stream, we can use the flatMap method: stream.flatMap(str -> Arrays.stream(str.split(” “)). This will result in a new stream containing all the words.

In summary, the map method maps each element to a new element and encapsulates it into a new stream; the flatMap method maps each element to a new stream and combines all the elements of the new streams into a new stream.

bannerAds