Search code examples
javajava-8option-type

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

  • 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.