Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if all true and reset a Boolean[] array using one-liner lambda expression of Java 8

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!

  1. Stream is cool, but it is not for this.
  2. BitSet (and its bit-wisely atomic counterpart AtomicBitSet) is more suitable for this (so accepted as the answer; thank others).
  3. Side-effects in map (Stream or generally functional programming) are discouraged.
  4. Arrays.stream(flags).forEach(flag -> flag = false) (in my code) does not set anything!
like image 213
hengxin Avatar asked Dec 28 '15 12:12

hengxin


People also ask

How do you check if all Booleans in an array are true?

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.

How do you handle exception thrown by lambda expression?

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.

What is lambda expression in Java 8 with example?

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.


1 Answers

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.

like image 87
Maroun Avatar answered Sep 22 '22 03:09

Maroun