Suppose I have a huge Boolean
array flags
:
Boolean[] flags = { true, false, true }; // 3 means "many"
I want to do two things on flags
:
true
and return an indicator;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 counterpart AtomicBitSet
) is more suitable for this (so accepted as the answer; thank others).map
(Stream
or generally functional programming) are discouraged.Arrays.stream(flags).forEach(flag -> flag = false)
(in my code) does not set anything!To check if all of the values in an array are equal to true , use the every() method to iterate over the array and compare each value to true , e.g. arr. every(value => value === true) . The every method will return true if the condition is met for all array elements.
A lambda expression cannot throw any checked exception until its corresponding functional interface declares a throws clause. An exception thrown by any lambda expression can be of the same type or sub-type of the exception declared in the throws clause of its functional interface.
Lambda expression is a new and important feature of Java which was included in Java SE 8. It provides a clear and concise way to represent one method interface using an expression. It is very useful in collection library. It helps to iterate, filter and extract data from collection.
Classic example for using the BitSet
class:
This class implements a vector of bits that grows as needed. Each component of the bit set has a boolean value.
In complexity terms, BitSet
uses ~1 bit for each boolean
value, which is way better than using big array of Boolean
objects.
Regarding checking of all bits are set or not (true or false), the API provides many useful methods - and they're really efficient.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With