I can do the conversion with code like this:
Object[] array = (Object[]) message.get(key);
boolean[] result = new boolean[array.length];
for (int i = 0; i < array.length; i++) {
result[i] = (boolean) array[i];
}
But, I was think that is possible to do the same conversion using Java 8 streams. I start to code something like this:
boolean[] = Arrays.stream(array)
.map(Boolean.class::cast)
.map(Boolean::booleanValue)
.toArray()
But this code doesn't work. Compiler says
incompatible types: java.lang.Object[] cannot be converted to boolean[]
I'm trying to understand what is the problem with the code. I think that map(Boolean::booleanValue)
would return a stream of boolean values I can collect with toArray
.
Object[]
andboolean[]
are types in Java that are not convertible, so actuallyObject[] = boolean[]
will not work either..toArray()
here is generic, soObject[]
is the best you can achieve. You may write your own collector to returnboolean[]
.toArray(IntFunction<A[]> generator)
to return a typed array. I added an answer as an example.CharStream
/BooleanStream
/etc. like there isIntStream
.)