-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.

6
  • tried that and no that still does not work Commented Jan 13, 2023 at 3:28
  • Then i expect you would need to use the Wrapper classes Boolean. This link is somewhat similar. I think its because streams dont work with primitives? Commented Jan 13, 2023 at 3: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. Commented Jan 13, 2023 at 3:39
  • 1
    Boolean[] isAvailableArray = class1List.stream().map(e -> e.isAvailable()).toArray(Boolean[]::new); Commented Jan 13, 2023 at 3: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. Commented Jan 13, 2023 at 7:59

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.