You are actually looking for: Optional.map . Then your code will look like this:
object.map(o -> "result" ) .orElseThrow(MyCustomException::new);
I would prefer to skip Optional
, if possible. You end up with nothing using Optional
here. A slightly different option:
public String getString(Object yourObject) { if (Objects.isNull(yourObject)) { // or use requireNonNull instead if NullPointerException suffices throw new MyCustomException(); } String result = ... // your string mapping function return result; }
If you already have an Optional
object due to another call, I still recommend that you use the map
method rather than isPresent
, etc. for one reason, that I find it more readable (obviously a subjective solution ;-)).
source share