0

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

3 Answers 3

4

What about

if (bList.contains(false)) {
  ...
Sign up to request clarification or add additional context in comments.

2 Comments

See my answer for a more general solution that allows you to evaluate a predicate over any type of Iterable.
That approach may be more generic but its functionality is not as obvious..:)
1

Consider extracting the loop to its method:

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

Comments

0

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

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.