Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to chain Optional#ifPresent() in lambda without nesting?

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();
}
like image 200
Zhro Avatar asked Sep 24 '26 03:09

Zhro


1 Answers

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.

like image 93
shmosel Avatar answered Sep 26 '26 15:09

shmosel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!