I have the following code block that requires that I check whether multiple nested variables are present. These were originally null checks that I replaced with Optional and ifPresent().
I would like to use ifPresent() instead of querying get() to mitigate potential runtime exceptions. But this is causing a lot of nesting.
Can I leverage lambdas in this example to achieve the same flow without the nesting?
void SomeMethod() {
procA().ifPresent(a -> {
procB(a).ifPresent(b -> {
// Do something
return;
});
});
throw new SomeException();
}
You can use flatMap:
procA().flatMap(this::procB).ifPresent(b -> {
// do something
});
As for the return statement, you can't return from the outer method inside the lambda. If you want to throw a custom exception when the value is missing, use orElseThrow:
B b = procA()
.flatMap(this::procB)
.orElseThrow(SomeException::new);
// do something with b
Or, of course you could just call get and let it throw a NoSuchElementException.
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