There are so many questions and threads about Optional API but I didn't found any for my case.
For example, I need first check emptiness of an Optional variable, for logging purpose, and then
check the value, if presents, with some predicate. Whatever check fails, I need to throw an exception.
Below is my real workaround for that
SomeValue value = someOptional.orElseThrow(() -> {
log.debug("nothing here");
return new NothingSpecialHereException();
});
if (!value.isSpecial()) {
log.debug("something here, but not special");
throw new NothingSpecialHereException();
}
When I was looking for an alternative solution for that, I tried something like that
SomeValue value = someOptional
.filter(SomeValue::isSpecial)
.orElseThrow(() -> {
log.debug("nothing special here"); // but this case for both "no value" and "value is not special"
return new NothingSpecialHereException();
});
I know that there's no any built-in solution for this situation in Java, but seems like I missing something like:
SomeValue value = someOptional
.ifNotPresent(() -> log.debug("nothing here")) // that method returns Optional for further invocatons
.filter(val -> {
if (!val.isSpecial()) {
log.debug("something here, but not special");
return false;
}
return true;
})
.orElseThrow(NothingSpecialHereException::new);
This is not the first time when I miss something like ifNotPresent or else* methods for use in the middle of pipe, not in the end. IMO sometimes that approach might be more readable, for example
optional
.map(...)
.filter(...)
.ifEmpty(...) // do smth after filter, maybe even throw
.map(...) // and continue processing
Maybe anyone encountered same problem? Or maybe I missed some better solution? Maybe there's a library that provides solutions for that?