How can I map Optional to another Optional if not present? [duplicate]

删除回忆录丶 提交于 2019-12-10 17:14:36

问题


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

回答1:


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

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



回答2:


You can create an optional based on a nullable value from other optionals:

public Optional<User> getUser(String id) {
    return Optional.ofNullable(
        cache.getUser(id).orElseGet(
            () -> repository.getUser(id).orElse(null)
        )
    );
}

But your current solution is clearly more readable.




回答3:


You can still use ?:

return (userFromCache.isPresent()) ? userFromCache : repository.getUser(id);

It's obviously an if in disguise but so is any other solution.



来源:https://stackoverflow.com/questions/53817555/how-can-i-map-optional-to-another-optional-if-not-present

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!