lundi 16 avril 2018

Use java lambda instead of if else

I have this code:

if(element.exist()){
    //do something
}

I want to convert to lambda style:

element.ifExist(el -> {
    //do something
});

with ifExist method likes this:

public void ifExist(Consumer<Element> consumer) {
    if (exist()) {
        consumer.accept(this);
    }
}

But now I want more else case to call:

element.ifExist(el -> {
    //do something
}).ifNotExist(el -> {
    //do something
});

I can write similar ifNotExist, but they cannot exclude (if the exist condition is true, no need to check ifNotExist), always have to check 2 times, how can I archive that?

Aucun commentaire:

Enregistrer un commentaire