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
.
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.
Firstly, let us take a boolean value. boolean val = false; Now, to convert it to Boolean object, use the valueOf() method. Boolean res = Boolean.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With