What is the most elegant way to check if all values in a boolean array are true?

后端 未结 11 873
后悔当初
后悔当初 2020-11-27 18:23

I have a boolean array in java:

boolean[] myArray = new boolean[10];

What\'s the most elegant way to check if all the values are true?

相关标签:
11条回答
  • 2020-11-27 18:56
    boolean alltrue = true;
    for(int i = 0; alltrue && i<booleanArray.length(); i++)
       alltrue &= booleanArray[i];
    

    I think this looks ok and behaves well...

    0 讨论(0)
  • 2020-11-27 18:57
    public static boolean areAllTrue(boolean[] array)
    {
        for(boolean b : array) if(!b) return false;
        return true;
    }
    
    0 讨论(0)
  • 2020-11-27 18:58

    I can't believe there's no BitSet solution.

    A BitSet is an abstraction over a set of bits so we don't have to use boolean[] for more advanced interactions anymore, because it already contains most of the needed methods. It's also pretty fast in batch operations since it internally uses long values to store the bits and doesn't therefore check every bit separately like we do with boolean[].

    BitSet myBitSet = new BitSet(10);
    // fills the bitset with ten true values
    myBitSet.set(0, 10);
    

    For your particular case, I'd use cardinality():

    if (myBitSet.cardinality() == myBitSet.size()) {
        // do something, there are no false bits in the bitset
    }
    

    Another alternative is using Guava:

    return Booleans.contains(myArray, true);
    
    0 讨论(0)
  • 2020-11-27 18:58

    OK. This is the "most elegant" solution I could come up with on the fly:

    boolean allTrue = !Arrays.toString(myArray).contains("f");
    

    Hope that helps!

    0 讨论(0)
  • 2020-11-27 19:00

    That line should be sufficient:

    BooleanUtils.and(boolean... array)

    but to calm the link-only purists:

    Performs an and on a set of booleans.

    0 讨论(0)
提交回复
热议问题