如果可选布尔值为真,如何执行操作?

2022-09-02 11:19:05

在Java 8中,我有一个变量,持有一个可选的布尔值。

我希望执行一个操作,如果可选不为空,并且包含的布尔值为真。

我梦想着类似的东西,这里有一个完整的例子: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."));
  }
}

答案 1

为了良好的秩序

if (spouseIsMale.orElse(false)) {
    System.out.println("There is a male spouse.");
}

清楚。


答案 2

可以通过以下方式实现该行为:.filter(b -> b)

spouseIsMale.filter(b -> b).ifPresent(b -> System.out.println("There is a male spouse."));

然而,它需要花费一些大脑执行时间几秒钟来理解这里发生了什么。