Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert short[] into List<Short> in Java with streams?

I figured I could extrapolate from this question but I can't

I can of course do

short[] shortarray = {0,1,2};
List<Short> shortList = new ArrayList<Short>();
for (Short s : shortarray) {
    shortList.add(s);
}

But I'm wondering how to do it with streams.

List<Short> shortList = Arrays.stream(shortarray).boxed()
                              .collect(Collectors.toList());

doesn't work for example but yields The method stream(T[]) in the type Arrays is not applicable for the arguments (short[])

like image 760
peer Avatar asked Feb 05 '20 09:02

peer


2 Answers

Why not

IntStream.range(0, shortarray.length)
         .mapToObj(s -> shortarray[s])
         .collect(Collectors.toList());
like image 135
ernest_k Avatar answered Oct 04 '22 22:10

ernest_k


As to why it does not work with a primitive short[]:

there is no Stream type of short. Streams only work for non primitive types or with IntStream, LongStream, and DoubleStream.

For it to work you would have to convert your shorts to a datatype with a compatible Stream, for example Short, or maybe to int for an IntStream (see ernest_k's answer).

like image 36
lugiorgi Avatar answered Oct 04 '22 23:10

lugiorgi