问题
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());
Is it possible to still use a lambda form for this that mitigates a call to get()?
My use-case is to avoid get() entirely where possible to prevent a possible unchecked exception being missed.
回答1:
My assumption is that you'd have to treat the other booleans 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);
NOTE
- Make sure to look at shinjw's solution here for a third example!
回答2:
Adding one more to variation the previous answer:
a.ifPresent(obj -> { if (b && c) list.add(obj); });
If a is present. Check then add the unwrapped object
来源:https://stackoverflow.com/questions/46782731/can-optional-ifpresent-be-used-in-a-larger-expression-to-mitigate-a-call-to-ge