Can Optional ifPresent() be used in a larger expre

2020-07-08 07:29发布

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.

2条回答
疯言疯语
2楼-- · 2020-07-08 07:41

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

查看更多
叛逆
3楼-- · 2020-07-08 07:42

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!
查看更多
登录 后发表回答