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?

public boolean validate(Optional<Object> obj) {

  if (obj.isPresent(obj) {
    var object = obj.get();
    // do something with the object
    return true

  } else {
    return false;
  }
}

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

public boolean validate(Optional<Object> obj) {

  return obj.ifPresentOrElse(
    object -> {
      // do something with the object
      return true;
    }, 
    () -> false
  );
}

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 :

obj.map(o->true).orElse(false);

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