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.
Simply put, if the value is present, then isPresent() would return true, and calling get() will return this value. Otherwise, it throws NoSuchElementException.
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).
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.
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.
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);
NOTE
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With