How can I map Optional to another Optional if not

2019-06-23 18:08发布

This question already has an answer here:

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

标签: java optional
3条回答
【Aperson】
2楼-- · 2019-06-23 18:41

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楼-- · 2019-06-23 18:47

You can still use ?:

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

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

查看更多
▲ chillily
4楼-- · 2019-06-23 18:49

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

return cache.getUser(id).or(() -> repository.getUser(id));
查看更多
登录 后发表回答