'Optional Of Nullable Executes orElse when map returns null
I have written a simple snippet
String aa = "aa";
String aaa = null;
String result = Optional.ofNullable(aa)
.map(s -> aaa)
.orElse("bb");
System.out.println(result);
orElse shall be executed when aa is null. But it is getting executed when map returns null as well.
My understanding is that orElse will be executed only aa is null. But will it be executed even when map return null?
Solution 1:[1]
I have to disagree with the accepted answer to look at the implementation, only the documentation is the source of the truth here. And in your case this is rather simple, you are doing (which basically maps to null)
.map(s -> aaa)
And the doc says:
If a value is present, apply the provided mapping function to it, and if the result is non-null, return an Optional describing the result. Otherwise return an empty Optional.
In your case the result of the s -> aaa lambda in the map operation is null, thus the part Otherwise return an empty Optional applies, thus the result of orElse is what you see.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Tony the Tech |
