可以在较大的表达式中使用可选的ifPresent()来缓解对get()的调用吗? [英] Can Optional ifPresent() be used in a larger expression to mitigate a call to get()?
本文介绍了可以在较大的表达式中使用可选的ifPresent()来缓解对get()的调用吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为避免调用 get()
,这会引发异常:
To avoid calling get()
which can throw an exception:
if (a.isPresent())
list.add(a.get());
我可以用以下代码替换此表达式:
I can replace this expression with:
a.ifPresent(list::add);
但如果我需要执行更大的表达式,例如:
But what if I need to perform a larger expression like:
if (a.isPresent() && b && c)
list.add(a.get());
是否仍然可以使用lambda表格来缓解对 get()
?
Is it possible to still use a lambda form for this that mitigates a call to get()
?
我的用例是避免 get()
完全尽可能防止错过可能未经检查的异常。
My use-case is to avoid get()
entirely where possible to prevent a possible unchecked exception being missed.
推荐答案
我的假设是你必须对待另一个 boolean
分开,但我可能错了。
My assumption is that you'd have to treat the other boolean
s separately, but I could be wrong.
if (b && c) {
a.ifPresent(list::add);
}
实际上,一个奇怪的解决方案可能是:
Actually, one weird solution could be:
a.filter(o -> b && c).ifPresent(list::add);
注意
- 请确保查看shinjw的解决方案此处以获取第三个示例!
- Make sure to look at shinjw's solution here for a third example!
这篇关于可以在较大的表达式中使用可选的ifPresent()来缓解对get()的调用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文