flatMap() method of Optional object in Java

As you all know, the Optional object is a generic object, its data type can be any object, and therefore, we can meet the case that its data type is also an Optional object, such as: Optional<Optional<String>>. To resolve this problem, Java introduces us to the flatMap() method so that Optional’s data type is simpler: Optional<String> for example.

For example, I have the following method:

To avoid the Null Pointer Exception, I will rewrite the above method with Optional object:

Now, if you use the above method with the map() method in the Optional object:

The return value of the map() method will be:

flatMap() method of Optional object in Java

As you can see, here the return result is an Optional object of the Optional object.

If we now use the flatMap() method instead of the map() method:

then the return value type will be much simpler:

flatMap() method of Optional object in Java

 

Add Comment