Skimming through the early access JavaDoc (ie. java.base
module) of the newest java-15, there is still no neat way to make the primitive boolean array work with Stream API together well. There is no new feature in the API with treating a primitive boolean array since java-8.
Note that there exist IntStream
, DoubleStream
and LongStream
, but nothing like BooleanStream
that would represent of a variation of a sequence of primitive booleans. Also the overloaded methods of Stream
are Stream::mapToInt
, Stream::mapToDouble
and Stream::mapToLong
, but not Stream::mapToBoolean
returning such hypothetical BooleanStream
.
Oracle seems to keep following this pattern, which could be found also in Collectors
. There is also no such support for float
primitives (there is for double
primitives instead). In my opinion, unlike of float
, the boolean
support would make sense to implement.
Back to the code... if you have a boxed boolean array (ie. Boolean[] array
), the things get easier:
Boolean[] array = ...
Stream<Boolean> streamOfBoxedBoolean1 = Arrays.stream(array);
Stream<Boolean> streamOfBoxedBoolean2 = Stream.of(array);
Otherwise you have to use more than one statement as said in this or this answer.
However, you asked (emphasizes mine):
way to convert given boolean[]
foo array into stream in Java-8 in one statement.
... there is actually a way to achieve this through one statement using a Spliterator
made from an Iterator
. It is definetly not nice but :
boolean[] array = ...
Stream<Boolean> stream = StreamSupport.stream(
Spliterators.spliteratorUnknownSize(
new Iterator<>() {
int index = 0;
@Override public boolean hasNext() { return index < array.length; }
@Override public Boolean next() { return array[index++]; }
}, 0), false);