问题描述
我有以下代码块,要求我检查是否存在多个嵌套变量.这些最初是我用Optional
和ifPresent()
代替的空检查.
I have the following code block that requires that I check whether multiple nested variables are present. These were originally null checks that I replaced with Optional
and ifPresent()
.
我想使用ifPresent()
而不是查询get()
来减轻潜在的运行时异常.但这会导致很多嵌套.
I would like to use ifPresent()
instead of querying get()
to mitigate potential runtime exceptions. But this is causing a lot of nesting.
在此示例中,我可以利用lambda来实现相同的流程而无需嵌套吗?
Can I leverage lambdas in this example to achieve the same flow without the nesting?
void SomeMethod() {
procA().ifPresent(a -> {
procB(a).ifPresent(b -> {
// Do something
return;
});
});
throw new SomeException();
}
推荐答案
您可以使用 flatMap
:
You can use flatMap
:
procA().flatMap(this::procB).ifPresent(b -> {
// do something
});
对于return语句,您不能从lambda内部的外部方法返回.如果要在缺少该值时引发自定义异常,请使用 orElseThrow
:
As for the return statement, you can't return from the outer method inside the lambda. If you want to throw a custom exception when the value is missing, use orElseThrow
:
B b = procA()
.flatMap(this::procB)
.orElseThrow(SomeException::new);
// do something with b
或者,当然,您可以只调用 get
并让其抛出NoSuchElementException
.
Or, of course you could just call get
and let it throw a NoSuchElementException
.
这篇关于如何在不嵌套的情况下在lambda中链接Optional#ifPresent()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!