I'm trying to make something like this:
private String getStringIfObjectIsPresent(Optional<Object> object){ object.ifPresent(() ->{ String result = "result"; //some logic with result and return it return result; }).orElseThrow(MyCustomException::new); }
This won't work, because ifPresent takes Consumer functional interface as parameter, which has void accept(T t). It cannot return any value. Is there any other way to do it ?
The orElseThrow method will return the value present in the Optional object. If the value is not present, then the supplier function passed as an argument is executed and an exception created on the function is thrown.
orElseThrow. Simply put, if the value is present, then isPresent() would return true, and calling get() will return this value. Otherwise, it throws NoSuchElementException.
Use the orElseThrow() method of Optional to get the contained value or throw an exception, if it hasn't been set. This is similar to calling get() , except that it allows for arbitrary exception types. The method takes a supplier that must return the exception to be thrown.
To return the value of an optional, or a default value if the optional has no value, you can use orElse(other) . Note that I rewrote your code for finding the longest name: you can directly use max(comparator) with a comparator comparing the length of each String.
Actually what you are searching is: Optional.map. Your code would then look like:
object.map(o -> "result" /* or your function */) .orElseThrow(MyCustomException::new);
I would rather omit passing the Optional
if you can. In the end you gain nothing using an Optional
here. A slightly other variant:
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 the Optional
-object due to another call, I would still recommend you to use the map
-method, instead of isPresent
, etc. for the single reason, that I find it more readable (clearly a subjective decision ;-)).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With