Java8 streaming api throws incompatible types: Object[] cannot be converted to Integer[] when converting String array to Integer array

Java8 streaming api throws incompatible types: Object[] cannot be converted to Integer[] when converting String array to Integer array … here is a solution to the problem.

Java8 streaming api throws incompatible types: Object[] cannot be converted to Integer[] when converting String array to Integer array

My following code:

String[] valStrs=data.split(";" );//data is a string
Integer[] vals=Arrays.stream(valStrs).map(Integer::valueOf).toArray();

Throwing :

error: incompatible types: Object[] cannot be converted to Integer[] [in Codec.java]
        Integer[] vals=Arrays.stream(valStrs).map(Integer::valueOf).toArray();

I

think I’m trying to get the String stream, then map the Strings into the Integer via Integer::valueOf and collect those Integers into an array.

So why does this error occur? A quick search but no answer.


Update:

In fact int[] arr= Arrays.stream(valStrs).mapToInt(Integer::p arseInt).toArray(); Works perfectly.

Solution

You must pass a constructor reference to the integer array to the toArray like this. Otherwise, it creates an Object[] by default.

Arrays.stream(valStrs).map(Integer::valueOf).toArray(Integer[]::new);

mapToInt creates an IntStream that is the toArray() function returning int[].

int[] toArray();

Instead, map(Integer::valueOf) creates a Stream<Integer> which is toArray returns Object[] unless otherwise specified. This is the implementation.

@Override
public final Object[] toArray() {
    return toArray(Object[]::new);
}

Calling toArray(Integer[]::new) calls this overloaded method.

public final <A> A[] toArray(IntFunction<A[]> generator)

Here is an excerpt from the documentation.

Returns an array containing the elements of this stream, using the
provided generator function to allocate the returned array.

generator a function which produces a new array of the desired type
and the provided length

Related Problems and Solutions