java Optional: a good way to not having to do nested ifPresent()

ealeon :

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

rgettman :

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 empty Optional.

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);
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=72308&siteId=1