Search code examples
javalogical-operatorsshort-circuiting

Short circuit logical operators over Iterable


Consider the following code, the loop can finish as soon as it hits a false value. Is there a better way than checking for false after each iteration?

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

Solution

  • Use Stream.allMatch which is a short-circuiting operation.

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