Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid isPresent() and get() in control logic

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?

like image 395
neu242 Avatar asked Jun 16 '15 06:06

neu242


2 Answers

You can use ifPresent instead of isPresent and get :

void doStuff(String someValue, Optional<Boolean> doIt) {
    doIt.ifPresent (b -> {
                             if (b) 
                                 trueMethod(someValue);  
                             else
                                 falseMethod(someValue);
                         });
}

EDIT: fixed my code, since you can't use the ternary operator if trueMethod and falseMethod don't return anything.

like image 166
Eran Avatar answered Sep 28 '22 10:09

Eran


This would be the functional approach using map:

Function<Boolean, Void> logic = isTrue -> {
  if (isTrue) trueMethod(someValue);
  else falseMethod(someValue);
  return null;
};
doIt.map(logic);

However, it is really ugly, mostly because of your "not-very-functional" trueMethod/falseMethod, which both return void (leading to the ugly return null).

like image 22
Rahel Lüthy Avatar answered Sep 28 '22 09:09

Rahel Lüthy