如果不存在,如何将Optional映射到另一个Optional?

问题描述:

我有以下Java 8代码:

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);
}

它工作正常,但我想知道如何将调用链接为不使用if.我已经尝试过使用orElseGet,但是它不允许返回另一个Optional<User>,而不能返回User.

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.

我想要这样的东西:

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

自Java 9开始,就有

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

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