Avoid isPresent () and get () in control logic

Is there a isPresent way to do the following in Java 8 by 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 did not try very hard?

+5
source share
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: My code has been fixed since you cannot use the ternary operator if trueMethod and falseMethod do not return anything.

+6
source

This will be a 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 , mainly because of your "not very functional" trueMethod / falseMethod , which returns void (leading to an ugly return null ).

0
source

All Articles