Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning from Java Optional ifPresent()

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.

like image 477
Friedrich 'Fred' Clausen Avatar asked Feb 26 '19 03:02

Friedrich 'Fred' Clausen


People also ask

How do I return an ifPresent value in Java 8?

If a value is present, isPresent() will return true and get() will return the value. Additional methods that depend on the presence or absence of a contained value are provided, such as orElse() (return a default value if value not present) and ifPresent() (execute a block of code if the value is present).

What is optional ifPresent?

The ifPresent method of the Optional class is an instance method that performs an action if the class instance contains a value. This method takes in the Consumer interface's implementation whose accept method will be called with the value of the optional instance as the parameter to the accept method.

What does Optional return in Java?

The Optional type was introduced in Java 8. It provides a clear and explicit way to convey the message that there may not be a value, without using null. When getting an Optional return type, we're likely to check if the value is missing, leading to fewer NullPointerExceptions in the applications.


2 Answers

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

return result.filter(a -> a.equals("something")).isPresent();
like image 169
Naman Avatar answered Sep 18 '22 13:09

Naman


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);
}
like image 33
shmosel Avatar answered Sep 19 '22 13:09

shmosel