I am new to using optionals in Java 8. I know the method orElseGet() takes a supplier and orElseThrow() also takes a supplier that throws an exception. orElseThrow() might be a good one to use if I can construct my own exception and do something when that exception is triggered.
My main goal is to use a method that will either get the unwrapped value, or if the optional wraps null, then to actually execute an entirely different function.
Looking for the closest thing to:
class DoInsteadClass {
public void doInstead() {
// Do this instead
}
}
Optional<String> myString = "Hello";
num.orElse(DoInsteadClass::doInstead);
If the only way to do this is orElseThrow(), and as long as I can handle the exception with the 'do this instead' code, that should be fine too. It just makes my codebase larger because I have to create a few different custom utility suppliers for the 2 or 3 cases where some of my optional values would return null.
The problem is, .ifPresent() invokes the specified consumer with the value, otherwise does nothing. I need it to DO SOMETHING if the value is null. My current code utilizes a custom workaround where I first check if the value is null, and if it is, execute a chosen function. Then the next statement is the one that checks for ifPresent(). So this is doing the same thing, I am just looking for a more sugar-coated, one statement version.
In JDK 9 there will be an
ifPresentOrElse
method that will allow it.For the time being, however, you may opt for the if statement, with
if(num.isPresent())
, or write your own reusableifPresentOrElse
method.