如何避免使用Optional.get和Optional.isPresent [英] How to avoid using Optional.get and Optional.isPresent

查看:1491
本文介绍了如何避免使用Optional.get和Optional.isPresent的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public ValueA map(ValueB valueB, Date date) {
    Optional<ValueC> valueCOpt = find(valueB);
    if (valueCOpt.isPresent()) {
        ValueC valueC = valueCOpt.get();
        // call many getters on valueC and do a lot of logic with it.
        return map(/*some parameters*/);
    }
    return null;
}

这看起来很丑.可选选项的优点在这里完全消失了.我读到应该使用mapflatMap而不是get.但是,如果我替换所有的吸气剂,真的有好处吗?

This seems quite ugly. The advantage of optionals is completely gone in here. I read that one should rather use map or flatMap instead of get. But is it really a benefit if I replace every getter like

valueC.getFieldA()

valueCOpt.map(ValueC::getFieldA)

您知道这里的一些常见或最佳做法吗?

Do you know some common or best practices here?

推荐答案

您可以使用

public ValueA map(ValueB valueB, Date date) {
    return find(valueB)
        .map(valueC -> {
            // call many getters on valueC and do a lot of logic with it.
            return map(/*some parameters*/);
        })
        .orElse(null);
}

关键点在于,如果可选函数不为空,则仅对映射函数求值,否则,结果将保留为空的可选函数.如果可选为空,则orElse(null)将返回null.

the key point is that the mapping function is only evaluated, if the optional is not empty, otherwise, the result stays an empty optional. orElse(null) will return null if the optional is empty.

这篇关于如何避免使用Optional.get和Optional.isPresent的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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