Anas Ismail
Anas Ismail

Reputation: 1

Combining multiple conditions in an if-statement

I have an array of booleans (The number of elements can be more than what is below):

boolean [] values = new boolean[] { false, true, false, false, true, true, false, false };

And I want to get the result of combining all the values within the array with the "&&" operator. In short, I wanna do something like this:

return values[0] && values[1] && values[2] && values[3] .... ;

But with a more cleaner and automatic way (using a loop for example)

Upvotes: 0

Views: 346

Answers (5)

shmosel
shmosel

Reputation: 50726

static boolean and(boolean... values) {
    for (boolean value : values) {
        if (!value) {
            return false;
        }
    }
    return true;
}

Or with Guava:

return !Booleans.contains(values, false);

Upvotes: 3

CharlieB
CharlieB

Reputation: 1030

You could try a foreach loop

boolean answerSoFar = true;
for(boolean value : values){
   answerSoFar = answerSoFar && value;
}
return answerSoFar;

(NB @shmosel got the following first) Since the AND condition is used for all the boolean values within the array, you could also return false whenever the false is found within the array; i.e.:

for(boolean value : values){
    if(!value){
      return false;
    }
}
return true;

Upvotes: 3

Elliott Frisch
Elliott Frisch

Reputation: 201467

In Java 8+, you could use an IntStream like

if (IntStream.range(0, values.length).allMatch(i -> values[i])) {
    // all of values are true
}

Upvotes: 1

Hung Cao
Hung Cao

Reputation: 3208

I am C# developer but I know you can use Stream in Java 8 to achieve it. Something like:

boolean [] values = new boolean[] { false, true, false, false, true, true, false, false };
Stream<Boolean> stream = IntStream.range(0, values.length).mapToObj(idx -> values[idx]); 
boolean test = stream.allMatch(i -> i);

Correct me if I am wrong. Thanks!

Upvotes: 0

Distwo
Distwo

Reputation: 11749

If you have one false in your array, then the result of && is false.

Knowing that, you just need to go through your array and check for false. If you find one, return false. If you don't return true. See shmosel answer for the code.

Upvotes: 0

Related Questions