I frequently have to do something as below
// some method
public T blah() {
    Optional<T> oneOp = getFromSomething();
    if (oneOp.isPresent()) {
        Optional<T> secondOp = getFromSomethingElse(oneOp.get())
        if (secondOp.isPresent()) {
            return secondOp.get()
        }
    }
    return DEFAULT_VALUE;
}
it's pretty cumbersome to keep checking for ifPresent() as if i am back to doing the null check
Use the flatMap method which will, if present, replace the Optional with another Optional, using the supplied Function.
If a value is present, returns the result of applying the given
Optional-bearing mapping function to the value, otherwise returns an emptyOptional.
Then, you can use orElse that will, if present, return the value or else the default value you supply.
If a value is present, returns the value, otherwise returns
other.
Here, I also turned the call to getFromSomethingElse into a method reference that will match the Function required by flatMap.
public T blah() {
    return getFromSomething().flatMap(this::getFromSomethingElse).orElse(DEFAULT_VALUE);
}
                        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