I'm looking to do a very basic if else on a boolean optional value. I'm missing something very basic I think
so the old school if else nest is like this
if (filterValue.isPresent()) {
if (filterValue.get()==true) {
method1();
} else {
method2();
}
} else {
method3();
}
I've tried various attempts at 2 replacements
filterValue.map(o -> o.TRUE ? method1() : method2()).orElse(method3());
and
filterValue.isPresent(filterValue.get().TRUE ? method1() : method2());
and can't quite seem to get the syntax ?
Could anyone point me in the right direction ?
map
doesn't work, because neither method1
nor method2
have a return value. And mapping to void
is not allowed.
Currently there is no real neat solution in Java 8, but if you happen to use Java 9 you achieve it with ifPresentOrElse(Consumer<T>, Runnable>)
:
filterValue.ifPresentOrElse(value -> {
if(value){
method1();
} else {
method2();
}
}, () -> method3());
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