Roland
Roland

Reputation: 7853

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;
    }
}

Upvotes: 0

Views: 113

Answers (3)

Roland
Roland

Reputation: 7853

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

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

Upvotes: 0

Reimeus
Reimeus

Reputation: 159784

What about

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

Upvotes: 4

Marko Topolnik
Marko Topolnik

Reputation: 200168

Consider extracting the loop to its method:

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

Upvotes: 1

Related Questions