-1

I have a list of Class1, which has a method isAvailable() which returns a boolean.

I am trying to create an array of boolean from this.

So far I have tried the below:

List<Class1> class1List;
boolean[] isAvailableArray =  class1List.stream()
                                        .map(e -> e.isAvailable())
                                        .toArray();

However this is throwing a can't convert from Object[] to boolean[] error.

What is the reason for this.

Abra
  • 19,142
  • 7
  • 29
  • 41
user3809938
  • 1,114
  • 3
  • 16
  • 35
  • tried that and no that still does not work – user3809938 Jan 13 '23 at 03:28
  • Then i expect you would need to use the Wrapper classes Boolean. This [link](https://stackoverflow.com/q/36507509/16034206) is somewhat similar. I think its because streams dont work with primitives? – experiment unit 1998X Jan 13 '23 at 03:29
  • The stream in your code and in general 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. – hiren Jan 13 '23 at 03:39
  • 1
    `Boolean[] isAvailableArray = class1List.stream().map(e -> e.isAvailable()).toArray(Boolean[]::new);` – experiment unit 1998X Jan 13 '23 at 03:45
  • 2
    Why do you even want a `boolean[]`? It’s very likely that whatever you want to do with the boolean array afterwards, can be done directly or at least, with an alternative way not requiring the boolean array. – Holger Jan 13 '23 at 07:59
  • Does this answer your question? [Convert a Object\[\] of booleans to a boolean\[\] using streams](https://stackoverflow.com/questions/36507509/convert-a-object-of-booleans-to-a-boolean-using-streams) – Didier L Jan 13 '23 at 14:47

1 Answers1

2

As you can see in the following example, the stream handles the primitive boolean values correctly (it creates Boolean objects). However, when toArray is used without a generator param (constructor), it falls back to an Object array.

import org.junit.jupiter.api.Test;

import java.util.ArrayList;
import java.util.List;

import static org.junit.jupiter.api.Assertions.assertTrue;

public class BooleanStream {
    public static class SomeClass {
        public boolean isAvailable() {
            return true;
        }
    }
    @Test
    public void testBoolean() {
        List<ByteArray.SomeClass> list = new ArrayList<>();
        ByteArray.SomeClass someClass = new ByteArray.SomeClass();
        list.add(someClass);

        Object[] isAvailableArray = list.stream().map(e -> e.isAvailable()).toArray();
        assertTrue(isAvailableArray[0] instanceof Boolean);
    }
}

As experiment-unit-1998x pointed out, the best solution is probably the generator param.

Roland J.
  • 76
  • 4