Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 Lambda on Primitive Boolean

Tags:

lambda

java-8

How do I make the following example work?

Boolean persistence =  Arrays.asList(new boolean[]{true, false})
                             .stream()
                             .filter(b -> b)
                             .findFirst().orElse(false); 

It works just fine when I replace boolean with Boolean.

like image 216
Klaus Avatar asked May 19 '26 07:05

Klaus


1 Answers

You cannot create a Stream of primitive booleans, this is the most efficient approach that does what you want.

boolean[] myArray = new boolean[]{ true, false };
boolean result = IntStream.range(0, myArray.length)
                          .anyMatch(index -> myArray[index]);

or you can replace the anyMatch with your approach of filter -findFirst if you prefer.

like image 171
Ousmane D. Avatar answered May 22 '26 07:05

Ousmane D.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!