Suppose I have a huge Boolean
array flags
:
Boolean[] flags = { true, false, true }; // 3 means "many"
I want to do two things on flags
:
- check whether all the elements are
true
and return an indicator; - reset all the elements to
false
.
Using lambda expression of Java 8, I can do them as follows:
indicator = Arrays.stream(flags).allMatch(flag -> flag);
Arrays.stream(flags).forEach(flag -> flag = false);
return indicator;
However this implementation scans flags
twice. Since flags
is huge, I don't want this. In addition, I do prefer the lambda way. Is there any way of implementing this checkIfAllTrueAndReset
semantics with (one-liner) lambda expression which scans flags
only once?
Related but not the same: What is the most elegant way to check if all values in a boolean array are true?
Note: I learn a lot from comments and answers. Thank you all!
Stream
is cool, but it is not for this.BitSet
(and its bit-wisely atomic counterpartAtomicBitSet
) is more suitable for this (so accepted as the answer; thank others).- Side-effects in
map
(Stream
or generally functional programming) are discouraged. Arrays.stream(flags).forEach(flag -> flag = false)
(in my code) does not set anything!