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:
1 2 3 4 |
public String findName() { // Do something return null; } |
To avoid the Null Pointer Exception, I will rewrite the above method with Optional object:
1 2 3 4 |
public Optional<String> findName() { // Do something return Optional.empty(); } |
Now, if you use the above method with the map() method in the Optional object:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
package com.huongdanjava.javaexample; import java.util.Optional; public class Example { public Optional<String> findName() { // Do something return Optional.empty(); } public static void main(String[] args) { Example e = new Example(); Optional<Example> opt = Optional.ofNullable(e); System.out.println(opt.map(x -> x.findName())); } } |
The return value of the map() method will be:
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
package com.huongdanjava.javaexample; import java.util.Optional; public class Example { public Optional<String> findName() { // Do something return Optional.empty(); } public static void main(String[] args) { Example e = new Example(); Optional<Example> opt = Optional.ofNullable(e); System.out.println(opt.flatMap(x -> x.findName())); } } |
then the return value type will be much simpler: