繁体   English   中英

可迭代的短路逻辑运算符

[英]Short circuit logical operators over Iterable

考虑下面的代码,循环一旦到达false值就可以结束。 有没有比每次迭代后检查false更好的方法了?

boolean result = true;
List<Boolean> bList = new ArrayList<>();
for (boolean b : bList) {
    result = result && b;
    if (!result) {
        break;
    }
}

关于什么

if (bList.contains(false)) {
  ...

考虑将循环提取到其方法:

boolean allTrue(List<Boolean> bools) {
  for (boolean b : bools)
    if (!b)
      return false;
  }
  return true;
}

使用Stream.allMatch这是一种短路操作。

List<Boolean> bList = new ArrayList<>();
boolean result = bList.stream().allMatch(b -> b);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM