Returning from Java Optional ifPresent()

13,294

Solution 1

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

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

Solution 2

How about mapping to a boolean?

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

Solution 3

While @nullpointer and @Ravindra showed how to merge the Optional with another condition, you'll have to do a bit more to be able to call APIs and do other stuff as you asked in the question. The following looks quite readable and concise in my opinion:

private static boolean checkSomethingIfPresent() {
    Optional<String> str = mightReturnAString();
    if (str.filter(s -> s.equals("something")).isPresent()) {
        //call APIs here using str.get()
        return true;
    }
    return false;
}

A better design would be to chain methods:

private static void checkSomethingIfPresent() {
    mightReturnFilteredString().ifPresent(s -> {
        //call APIs here
    });
}

private static Optional<String> mightReturnFilteredString() {
    return mightReturnAString().filter(s -> s.equals("something"));
}

private static Optional<String> mightReturnAString() {
    return Optional.of("something");
}

Solution 4

The ideal solution is “command-query separation”: Make one method (command) for doing something with the string if it is present. And another method (query) to tell you whether it was there.

However, we don’t live an ideal world, and perfect solutions are never possible. If in your situation you cannot separate command and query, my taste is for the idea already presented by shmosel: map to a boolean. As a detail I would use filter rather than the inner if statement:

public boolean checkSomethingIfPresent() {
    return mightReturnAString().filter(item -> item.equals("something"))
            .map(item -> {
                // Do some other stuff like use "something" in API calls
                return true; // (compiles)
            })
            .orElse(false);
}

What I don’t like about it is that the call chain has a side effect, which is not normally expected except from ifPresent and ifPresentOrElse (and orElseThrow, of course).

If we insist on using ifPresent to make the side effect clearer, that is possible:

    AtomicBoolean result = new AtomicBoolean(false);
    mightReturnAString().filter(item -> item.equals("something"))
            .ifPresent(item -> {
                // Do some other stuff like use "something" in API calls
                result.set(true);
            });
    return result.get();

I use AtomicBoolean as a container for the result since we would not be allowed to assign to a primitive boolean from within the lambda. We don’t need its atomicity, but it doesn’t harm either.

Link: Command–query separation on Wikipedia

Share:
13,294
Friedrich 'Fred' Clausen
Author by

Friedrich 'Fred' Clausen

I'm an build engineer living in Sydney working on things such as CI pipeline automation Gradle Infrastructure code like Terraform and Helm Configuration Management Glue code and also some personal projects using Swift on iOS and studying the computer science book Concrete Mathematics.

Updated on July 07, 2022

Comments

  • Friedrich 'Fred' Clausen
    Friedrich 'Fred' Clausen over 1 year

    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.