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

后端 未结 11 872
后悔当初
后悔当初 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:40

    It depends how many times you're going to want to find this information, if more than once:

    Set<Boolean> flags = new HashSet<Boolean>(myArray);
    flags.contains(false);
    

    Otherwise a short circuited loop:

    for (i = 0; i < myArray.length; i++) {
      if (!myArray[i]) return false;
    }
    return true;
    
    0 讨论(0)
  • 2020-11-27 18:40

    You can check all value items are true or false by compare your array with the other boolean array via Arrays.equal method like below example :

    private boolean isCheckedAnswer(List<Answer> array) {
        boolean[] isSelectedChecks = new boolean[array.size()];
        for (int i = 0; i < array.size(); i++) {
            isSelectedChecks[i] = array.get(i).isChecked();
        }
    
        boolean[] isAllFalse = new boolean[array.size()];
        for (int i = 0; i < array.size(); i++) {
            isAllFalse[i] = false;
        }
    
        return !Arrays.equals(isSelectedChecks, isAllFalse);
    }
    
    0 讨论(0)
  • 2020-11-27 18:44
    Arrays.asList(myArray).contains(false)
    
    0 讨论(0)
  • 2020-11-27 18:45

    In Java 8+, you can create an IntStream in the range of 0 to myArray.length and check that all values are true in the corresponding (primitive) array with something like,

    return IntStream.range(0, myArray.length).allMatch(i -> myArray[i]);
    
    0 讨论(0)
  • 2020-11-27 18:50

    This is probably not faster, and definitely not very readable. So, for the sake of colorful solutions...

    int i = array.length()-1;
    for(; i > -1 && array[i]; i--);
    return i==-1
    
    0 讨论(0)
  • 2020-11-27 18:51

    In Java 8, you could do:

    boolean isAllTrue = Arrays.asList(myArray).stream().allMatch(val -> val == true);
    

    Or even shorter:

    boolean isAllTrue = Arrays.stream(myArray).allMatch(Boolean::valueOf);
    

    Note: You need Boolean[] for this solution to work. Because you can't have a primitives List.

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