Optional.ofNullable和方法链接 [英] Optional.ofNullable and method chaining

查看:2712
本文介绍了Optional.ofNullable和方法链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 Optional.ofNullable 方法感到惊讶。有一天我写了一个应该返回一个可选的函数:

I was surprised by Optional.ofNullable method. Some day I wrote a function that supposed to return an Optional:

private Optional<Integer> extractFirstValueFrom(InsightsResponse insight) {
    return Optional.ofNullable(insight.getValues().get(0).getValue());
}

我错误地认为 Optional.ofNullable 将阻止参数表达式中的任何 NullPointerExceptions

I mistakenly thought that Optional.ofNullable will prevent any NullPointerExceptions inside of argument expression.

现在我想我知道这是非常愚蠢的想法。 Java必须首先解析参数以将其传递给 Optional.ofNullable 调用。

Now I think I know that it was very foolish idea. Java have to resolve arguments first to pass it to Optional.ofNullable invocation.

但我有一个问题。有没有一个很好的方法来实现我的目标?我想从表达式 insight.getValues()。get(0).getValue()获取一些整数值或null。 Null可以是以下每个表达式: insight.getValues() insight.getValues()。get(0)

But I have a question. Is there a nice and good way to accomplish my goal? I would like to obtain from expression insight.getValues().get(0).getValue() some Integer value or null. Null can be each one of the expressions: insight.getValues() or insight.getValues().get(0).

我知道我可以把它放在try / catch块中,但我想知道是否有更优雅的解决方案。

I know that I can just put this in try/catch block but I am wondering if there is more elegant solution.

推荐答案

如果您不知道什么是 null ,或者想要检查 null ,唯一的方法是将调用链接到 Optional.map

If you have no idea what can be null, or want to check everything for null, the only way is to chain calls to Optional.map:


如果存在值,则将提供的映射函数应用于该值,如果结果为非null,则返回描述结果的Optional。否则返回一个空的可选。

If a value is present, apply the provided mapping function to it, and if the result is non-null, return an Optional describing the result. Otherwise return an empty Optional.

因此,如果映射器返回 null ,将返回一个空的可选,这允许连锁电话。

As such, if the mapper return null, an empty Optional will be returned, which allows to chain calls.

Optional.ofNullable(insight)
        .map(i -> i.getValues())
        .map(values -> values.get(0))
        .map(v -> v.getValue())
        .orElse(0);

orElse(0) 允许返回默认值0(如果有的话) mapper返回 null

这篇关于Optional.ofNullable和方法链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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