Convert a Object[] of booleans to a boolean[] using streams
No, because map(Boolean::booleanValue)
expands to
map((Boolean value) -> (Boolean)value.booleanValue());
(note the autoboxing inserted by the compiler, because the function passed to map()
has to return an Object
, not a boolean
)
This is why the Java8 streams include a whole bunch of specialized classes (IntStream
, LongStream
, and DoubleStream
). Sadly, there is no specialized stream class for boolean
.
The only streams of primitive type are IntStream
, LongStream
and DoubleStream
. In particular there is no BooleanStream
and there is no idiomatic way to convert a Stream<Boolean>
to a boolean[]
.
If you need this functionality frequently you can use a utility class like this:
public final class BooleanUtils { private BooleanUtils() {} public static boolean[] listToArray(List<Boolean> list) { int length = list.size(); boolean[] arr = new boolean[length]; for (int i = 0; i < length; i++) arr[i] = list.get(i); return arr; } public static final Collector<Boolean, ?, boolean[]> TO_BOOLEAN_ARRAY = Collectors.collectingAndThen(Collectors.toList(), BooleanUtils::listToArray);}
Then, given a Stream<Boolean>
, you will be able to do:
boolean[] arr = stream.collect(BooleanUtils.TO_BOOLEAN_ARRAY);
If you're not opposed to the idea of getting a list instead, you can simply perform collect
as your terminal action:
final List<Boolean> boolList = Arrays.stream(array) .map(Boolean.class::cast) .map(Boolean::booleanValue) .collect(Collectors.toList());
The stream as defined here is only capable of producing an Object[]
if you attempt to collect it into an array. Using a list will at least allow you to maintain the type you want to convert it into.