Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Optional ifPresent() be used in a larger expression to mitigate a call to 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());

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.

like image 776
Zhro Avatar asked Oct 17 '17 04:10

Zhro


People also ask

What exception is thrown by optional get () when not nested within optional isPresent ()?

Simply put, if the value is present, then isPresent() would return true, and calling get() will return this value. Otherwise, it throws NoSuchElementException.

When should we use optional in Java?

Optional is a new type introduced in Java 8. It is used to represent a value that may or may not be present. In other words, an Optional object can either contain a non-null value (in which case it is considered present) or it can contain no value at all (in which case it is considered empty).

What is the use of optional?

Optional is a container object used to contain not-null objects. Optional object is used to represent null with absent value. This class has various utility methods to facilitate code to handle values as 'available' or 'not available' instead of checking null values.

Why is optional required?

Optional is intended to provide a limited mechanism for library method return types where there needed to be a clear way to represent “no result," and using null for such was overwhelmingly likely to cause errors.


2 Answers

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!
like image 100
Jacob G. Avatar answered Oct 20 '22 01:10

Jacob G.


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

like image 40
shinjw Avatar answered Oct 20 '22 01:10

shinjw