如果不存在,如何将Optional映射到另一个Optional? [英] How can I map Optional to another Optional if not present?

查看:108
本文介绍了如果不存在,如何将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));

这篇关于如果不存在,如何将Optional映射到另一个Optional?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆