Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a Object[] of booleans to a boolean[] using streams

Tags:

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.

like image 850
drizzt.dourden Avatar asked Apr 08 '16 19:04

drizzt.dourden


People also ask

How do you convert to boolean?

Using parseBoolean() method of Boolean class This is the most common method to convert String to boolean. This method is used to convert a given string to its primitive boolean value. If the given string contains the value true ( ignoring cases), then this method returns true.

How do you cast boolean to boolean?

Firstly, let us take a boolean value. boolean val = false; Now, to convert it to Boolean object, use the valueOf() method. Boolean res = Boolean.

How do you cast a boolean to an object?

To convert Boolean Primitive to Boolean object, use the valueOf() method in Java. Firstly, let us take a boolean primitive. boolean val = false; To convert it into an object, use the valueOf() method and set the argument as the boolean primitive.


1 Answers

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.

like image 171
Darth Android Avatar answered Sep 21 '22 13:09

Darth Android