Returning from Java Optional ifPresent()

optional ifpresent return value
java optional ifpresent throw exception
java optional ifpresentorelse
java optional get if present else null
optional.ofnullable ifpresent
java return optional or null
java 8 ifpresent
java optional compare if present

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.


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

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

java.util.Optional.ifPresent java code examples, Checking the presence of a value isPresent() method returns true if the Optional contains a non-null value, otherwise it returns false. ifPresent() method allows you to pass a Consumer function that is executed if a value is present inside the Optional object. It does nothing if the Optional is empty. Java 8 Optional - Replace your get() calls. 1. Optional orElse example. It returns the value if is present, or the other specified otherwise. Let’s see an example: @Test public void 2. Optional orElseThrow example. 3. Optional filter example. 4. Optional map example. 5. Optional flatMap example.


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

Java Optional Tutorial with Examples, Optional ifPresent example IfPresent, that it's different from isPresent, accept a function, a Consumer , and executes it only if the value is present. Basically ifPresent() should be used for function that does side-effect (returning a void). Before Java 8, if we wanted to check whether something is null, we had to write crappy null checks. Today, we have better alternatives. Consider a situation when we have a method that returns a


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

Java 8 Optional, This page shows Java code examples of java.util.Optional#ifPresent. ifPresent( args::putAll); return new LocalCall<>("grains.set", Optional.empty(),� If a value is present, apply the provided Optional -bearing mapping function to it, return that result, otherwise return an empty Optional. This method is similar to map (Function), but the provided mapper is one whose result is already an Optional, and if invoked, flatMap does not wrap it with an additional Optional.


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

Java Code Examples for java.util.Optional#ifPresent, Return the contained value, if present, otherwise throw an exception to be created by the provided supplier. String � toString(). Returns a non-empty string� The ifPresentOrElse (Consumer, Runnable) method of java.util. Optional class helps us to perform the specified Consumer action the value of this Optional object. If a value is not present in this Optional, then this method performs the given empty-based Runnable emptyAction, passed as the second parameter


Optional (Java Platform SE 8 ), Learn the best practices and when to return the Optional type in Java. The ifPresent() method enables us to run some code on the wrapped� public <U> Optional<U> map​(Function<? super T,​? extends U> mapper) If a value is present, returns an Optionaldescribing (as if by ofNullable(T)) the result of applying the given mapping function to the value, otherwise returns an empty Optional.


Guide To Java 8 Optional, Before Java 8, programmers would return null instead of Optional. When using ifPresent , this looks like killing two birds with one stone. The orElse() method returns the wrapped value if it's present and its argument,� If the Optional contains a non-null value and the value matches the given predicate, then filter() method returns an Optional with that value, otherwise it returns an empty Optional. So, the function inside ifPresent() in the above example will be called if and only if the Optional contains a user and user is a MALE.


Java 8 Optional Usage and Best Practices, Instead of using ifPresent() and get(), it's better to use OrElse() method which can return a default value if Optional doesn't contain a value. Using plain get() is�