Patan
Patan

Reputation: 17883

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?

Upvotes: 5

Views: 8868

Answers (2)

Eugene
Eugene

Reputation: 120858

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.

Upvotes: 3

Naman
Naman

Reputation: 31878

My understanding is that orElse will be executed only aa is null. But will it be executed even when map return null?

That's better explained by the implementation of the Optional.map function itself :

//         return type                 function to map
public <U> Optional<U> map(Function<? super T, ? extends U> mapper) {
    Objects.requireNonNull(mapper); // null check 
    if (!isPresent()) {
        return empty();    // could be true when 'aa' is null in your case
    } else {
        return Optional.ofNullable(mapper.apply(value)); // using Optional.ofNullable itself
    }
 }

Hence, if on applying the mapper i.e. in your case s -> aaa returns null, the map operation would return Optional.empty followed by orElse branching.

Upvotes: 5

Related Questions