Is there a prettier way of doing the following in Java 8, avoiding isPresent
and get
?
void doStuff(String someValue, Optional<Boolean> doIt) {
if (doIt.isPresent()) {
if (doIt.get()) {
trueMethod(someValue);
} else {
falseMethod(someValue);
}
}
}
I tried using map
, without success. But I probably didn't try hard enough?
This would be the functional approach using
map
:However, it is really ugly, mostly because of your "not-very-functional"
trueMethod
/falseMethod
, which both returnvoid
(leading to the uglyreturn null
).You can use
ifPresent
instead ofisPresent
andget
:EDIT: fixed my code, since you can't use the ternary operator if
trueMethod
andfalseMethod
don't return anything.