java – Optional. Ofnullable and method links

I'm interested in optional The ofnullable method surprised me One day I wrote a function that should return an optional function:

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

I mistakenly believe that optional Ofnullable blocks any nullpointerexceptions within the parameter expression

Now I think I know it's a very stupid idea Java must first parse the parameter and pass it to optional Ofnullable call

But I have a problem Is there a good way to achieve my goal? I want to start with the expression insight Getvalues() get (0) Getvalue() some integer values or null Null can be each expression: insight Getvalues() or insight getValues(). get(0).

I know I can put it in the try / catch block, but I wonder if there is a more elegant solution

Solution

If you don't know what can be null, or want to check that everything is null, the only way is to link the call to optional map:

Therefore, if the mapper returns null, it will return an empty option, which allows the link call

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

If any mapper returns null, the final call to orelse (0) allows the default value of 0

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>