Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

functional if else on a Boolean

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 ?

like image 959
gringogordo Avatar asked Dec 24 '22 04:12

gringogordo


1 Answers

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());
like image 156
Lino Avatar answered Jan 09 '23 02:01

Lino