How can I map Optional to another Optional if not present?

Héctor :

I have this Java 8 code:

public Optional<User> getUser(String id) {
    Optional<User> userFromCache = cache.getUser(id);
    if (userFromCache.isPresent()) {
        return userFromCache;
    }
    return repository.getUser(id);
}

It works fine but I'm wondering how can I chain the call to not to use if. I have tried with orElseGet but it doesn't allow to return another Optional<User> but a User.

I want something like this:

Optional<User> userFromCache = cache.getUser(id)
    .orElseGet(() -> repository.getUser(id));
khelwood :

Since Java 9, there is Optional.or. It accepts a supplier for another Optional.

return cache.getUser(id).or(() -> repository.getUser(id));

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=71888&siteId=1