Avoid isPresent() and get() in control logic

强颜欢笑 提交于 2019-12-22 06:33:11

问题


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?


回答1:


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.




回答2:


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).



来源:https://stackoverflow.com/questions/30860584/avoid-ispresent-and-get-in-control-logic

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!