Can Optional ifPresent() be used in a larger expression to mitigate a call to get()?

Zhro :

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.

Jacob G. :

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!

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=441309&siteId=1