Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

java-8

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

like image 826
ealeon Avatar asked Dec 13 '22 12:12

ealeon


1 Answers

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);
}
like image 148
rgettman Avatar answered Feb 23 '23 02:02

rgettman