Nuñito Calzada
Nuñito Calzada

Reputation: 2066

Java 8 - Returning an empty Optional

I have this method that I want to return an empty optional is nothing is found

@Override
public Optional<Menu> findBySymbol (String symbol) {
    Optional<Menu> menu = 
                    StreamSupport
                    .stream(cachedMenus.get(ALL_CURRENCIES_KEY).spliterator(), true)
                    .findFirst();

    return menu.orElse(Optional.empty());

}

but I got a compilation error: Type mismatch: cannot convert from Optional<Object> to Menu

Upvotes: 1

Views: 717

Answers (3)

davidxxx
davidxxx

Reputation: 131346

Optional.orElse(T other) returns the value if presents, otherwise the parameter is returned as value.
So the compiler expects as parameter type a variable with the same type as the generic used for the Optional. Here you have a Optional<Menu>, so a Menu is expected.
Whereas the compilation error here :

return menu.orElse(Optional.empty());

Note that the main purpose of Optional is indeed to wrap the value if exits or to wrap empty (instead of null).
So to get an empty optional from a stream processing such as findFirst() or findAny(), you don't need to do anything.
So as others said, that is enough :

return  StreamSupport
        .stream(cachedMenus.get(ALL_CURRENCIES_KEY).spliterator(), true)
        .findFirst();

Upvotes: 5

Ousmane D.
Ousmane D.

Reputation: 56423

just return:

return StreamSupport.stream(cachedMenus.get(ALL_CURRENCIES_KEY).spliterator(), true)
                    .findFirst();

this will return the first element wrapped in an Optional or empty Optional if the source is empty.

Upvotes: 5

Eugene
Eugene

Reputation: 120848

why not just return it?

return StreamSupport.stream(cachedMenus.get(ALL_CURRENCIES_KEY).spliterator(), true)
                     .findFirst();

Upvotes: 9

Related Questions