java 如果可选布尔值为真,如何执行操作?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46766422/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to do an action if an optional boolean is true?
提问by slartidan
In Java 8, I have a variable, holding an optional boolean.
在 Java 8 中,我有一个变量,包含一个可选的布尔值。
I want an action to be executed, if the optional is not empty, and the contained boolean is true.
如果可选项不为空,并且包含的布尔值为真,我希望执行一个操作。
I am dreaming about something like ifPresentAndTrue
, here a full example:
我梦想着类似的东西ifPresentAndTrue
,这里有一个完整的例子:
import java.util.Optional;
public class X {
public static void main(String[] args) {
Optional<Boolean> spouseIsMale = Optional.of(true);
spouseIsMale.ifPresentAndTrue(b -> System.out.println("There is a male spouse."));
}
}
回答by Joop Eggen
For good order
为了良好的秩序
if (spouseIsMale.orElse(false)) {
System.out.println("There is a male spouse.");
}
Clear.
清除。
回答by slartidan
It is possible to achieve that behaviour with .filter(b -> b)
:
可以通过以下方式实现该行为.filter(b -> b)
:
spouseIsMale.filter(b -> b).ifPresent(b -> System.out.println("There is a male spouse."));
However, it costs some brain execution timeseconds to understand what is going on here.
然而,理解这里发生的事情需要花费一些大脑执行时间。
回答by Sanjay K S
For those looking to write this without traditional
if(condition){ //Do something if true; }
对于那些希望在没有传统的情况下编写此内容的人
if(condition){ //Do something if true; }
Optional.of(Boolean.True)
.filter(Boolean::booleanValue)
.map(bool -> { /*Do something if true;*/ })
回答by dstibbe
All of the above answers combined:
综合以上所有答案:
spouseIsMale
.filter(Boolean::booleanValue)
.ifPresent(
value -> System.out.println("There is a male spouse.")
);
回答by Mudassir Shahzad
What I usually use is (I also check for the null value):
我通常使用的是(我也检查空值):
Optional.ofNullable(booleanValue).filter(p -> p).map(m -> callFunctionWhenTrue()).orElse(doSomethingWhenFalse());
This has three parts:
这包括三个部分:
Optional.ofNullable(booleanValue)
- Checks for null value.filter(p -> p).map(m -> callFunctionWhenTrue())
- Filter checks for boolean value true and appyly the map function.orElse(doSomethingWhenFalse())
- This part will execute if the boolean value is false
Optional.ofNullable(booleanValue)
- 检查空值.filter(p -> p).map(m -> callFunctionWhenTrue())
- 过滤检查布尔值是否为真并应用地图功能.orElse(doSomethingWhenFalse())
- 如果布尔值为假,这部分将执行
回答by Sergey Prokofiev
You can shrink it a little bit.
你可以把它缩小一点。
Optional<Boolean> spouseIsMale= Optional.of(true);
spouseIsMale.ifPresent(v -> { if (v) System.out.println("There is a male spouse.");});