map() vs flatMap in Java
flatMap()
and map()
are useful methods used in functional programming with Stream
, Optional
, and, CompletableFuture
. Though they seem similar, they serve different purposes.
Map()
In Optional, map()
applies the function to the value the optional contains and wraps the result in a new Optional. In the case the optional is empty, it just returns an empty Optional.
Let’s take a look at the examples below.
Because the optional named name
is not empty in the example above, map() transforms the value the optional contains and wraps the output in a new Optional. However, it returns an empty Optional as the name optional is empty in the one below.
In Streams, map() applies to the function to the elements of the stream and produces another stream consisting of the results.
But what about nested Optionals or Streams? In this case, flatMap()
comes to the rescue.
2. FlatMap()
flatMap()
is a combination of map()
and flattening, meaning it applies a transformation and flattens the result to avoid nested structures.
In Optional, it helps to flatten a nested optional.
Let’s take the following example which is closer to a real-life problem.
Since both the Address field from the user object and its city field are optional, accessing the city field from the User object through the address field can be a bit complicated. The flatMap() method helps safely retrieve the city field from the User object, avoiding nested Optional instances.
In Stream, flatMap() helps similarly by flattening nested streams.
Thanks for reading!