Returning from Java Optional ifPresent()

Fred Clausen :

I understand you can't return from a ifPresent() so this example does not work:

public boolean checkSomethingIfPresent() {
    mightReturnAString().ifPresent((item) -> {
        if (item.equals("something")) {
            // Do some other stuff like use "something" in API calls
            return true; // Does not compile
        }
    });
    return false;
}

Where mightReturnAString() could return a valid string or an empty optional. What I have done that works is:

public boolean checkSomethingIsPresent() {
    Optional<String> result = mightReturnAString();

    if (result.isPresent()) {
        String item = result.get();
        if (item.equals("something") {
            // Do some other stuff like use "something" in API calls
            return true;
        }
    }
    return false;
}

which is longer and does not feel much different to just checking for nulls in the first place. I feel like there must be a more succinct way using Optional.

Naman :

I think all you're looking for is simply filter and check for the presence then:

return result.filter(a -> a.equals("something")).isPresent();

Guess you like

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