Joshua Goldberg
Joshua Goldberg

Reputation: 5333

A way to return an Optional value if present without saving it or deriving it twice?

I'd like to do something like the following, where x would be returned from the containing function and not "continue processing" if the optional is present:

stuff().that().returns().optional().ifPresent(x -> return x);
// otherwise continue processing
...
return alternateResult;

Something like this would be ok, too:

if (stuff().that().returns().optional().isPresent()) {
    return thatResult;
}
// otherwise continue processing
...
return alternateResult;

But ideas like these don't work: return inside the lambda just returns from the lambda, and in the 2nd case, I don't have the value back inside the closure after checking isPresent(). Is there a more concise idiom I can use?

Upvotes: 2

Views: 567

Answers (2)

Alex - GlassEditor.com
Alex - GlassEditor.com

Reputation: 15507

If you can do the rest of the processing inside a lambda you could use orElseGet:

return stuff().that().returns().optional().orElseGet(() -> {
    ...
    return alternateResult;
});

Upvotes: 4

Joshua Goldberg
Joshua Goldberg

Reputation: 5333

The best I've come up with so far. Is this the best there is?

Optional<ExplicitType> maybeResult = stuff().that().returns().optional();
if (maybeResult.isPresent()) {
    return maybeResult.get();
}
// otherwise continue processing
...
return alternateResult;

Upvotes: 1

Related Questions