Let's consider the following class
class A{
void met(int i){
//do somthing
}
}
and let's consider that we have an optional object of this class like:
Optional<A> a;
is it possible to call the method met on the object a without the need to check whether a refers to a full object or just empty (null). Something like:
a.map(A::met(5));
Unfortunately this code doesn't compile. How can this be done?
There are two reasons why this can't work:
a.map(A::met(5));
met returns nothing, and map must map the input Optional to an output Optional.What you need is :
a.ifPresent(x->x.met(5));
Another option :
a.orElse(new A()).met(5);
This will execute met(5) on a dummy instance if a is empty, so it's probably not the best way.
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