在控制逻辑中避免使用isPresent()和get() [英] Avoid isPresent() and get() in control logic

查看:874
本文介绍了在控制逻辑中避免使用isPresent()和get()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java 8中有没有更好的方法来避免 isPresent get

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

我试过使用 map ,但没有成功。但我可能没有努力去努力?

c>而不是 isPresent get



<$ p $ (b)
(b)
trueMethod(someValue) ;
else
falseMethod(someValue);
});

$ / code>

编辑:修复我的代码,因为你不能使用三元运算符if trueMethod falseMethod 不会返回任何内容。


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?

解决方案

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.

这篇关于在控制逻辑中避免使用isPresent()和get()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆