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

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

提交回复
热议问题