Skip to content
Advertisement

returning early from a method if an Optional is empty

Is there a more functional way to return early from a method if an Optional is empty than this?

JavaScript

What I’m looking for is something like Optional.ifPresentOrElse, but I can’t use that in this case, because the lambda arguments it takes (Consumer and Runnable) both have void return types.

If the lambda arguments were instead of type Function, and the return value of ifPresentOrElse is whatever the invoked lambda returns, I could do this instead

JavaScript

But there doesn’t seem to be anything like this in the Optional API. Is there a way to improve upon the first example from a functional point-of-view?

Advertisement

Answer

You can use a combination of map and orElse like the following :

JavaScript

inside the map you can // do something with the object and decide whether to return true or not.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement