java8 stream apis throwing incompatible types: Object[] cannot be converted to Integer[] when converting String array to Integer array

ZhaoGang :

My below codes:

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

is 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 am trying to get a String stream, then map String into Integer by Integer::valueOf, and collect these Integer into an array.

So why this error? Did a quick search and cann't find the answer.


UPDATE:

With the fact that int[] arr= Arrays.stream(valStrs).mapToInt(Integer::parseInt).toArray(); works perfectly.

Ravindra Ranwala :

You have to pass the constructor reference to the integer array in to the toArray like this. Otherwise it will create an Object[] by default.

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

mapToInt creates an IntStream, and it's toArray() function returns an int[]. Here's the declaration.

int[] toArray();

Conversely, map(Integer::valueOf) creates a Stream<Integer> and it's toArray returns an Object[] unless otherwise specified. Here's the implementation.

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

The invocation of toArray(Integer[]::new) will call this overloaded method.

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

Here's 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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=98151&siteId=1