9

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[])

peer
  • 4,171
  • 8
  • 42
  • 73

3 Answers3

11

Why not

IntStream.range(0, shortarray.length)
         .mapToObj(s -> shortarray[s])
         .collect(Collectors.toList());
ernest_k
  • 44,416
  • 5
  • 53
  • 99
  • Why `mapToObj` and not `mapToInt` (or plain `map`)? using an `IntStream` instead of `Stream` should be preferable in almost all situations when one is handling primitive ints or shorts. – Polygnome Feb 05 '20 at 09:26
  • `mapToInt` finally collect a `List` instance, not a `List`. – Sachith Dickwella Feb 05 '20 at 09:27
  • 1
    @Polygnome I believe you have a point, but the OP is collecting elements into a `List`, so boxing can't be avoided. – ernest_k Feb 05 '20 at 09:28
  • 1
    @Polygnome “in almost all situations”, except when the task is to produce a `List`. Not that I ever encountered such a need in real life… – Holger Feb 05 '20 at 11:24
1

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

StayOnTarget
  • 11,743
  • 10
  • 52
  • 81
lugiorgi
  • 473
  • 1
  • 4
  • 12
  • Yes, you can not cast it, but you can convert each entry. I clarified that in an edit. I feel the "why" is also important for an answer and should be included. – lugiorgi Feb 05 '20 at 09:30
0

There is another way you can convert short array into a collection.

  1. Convert short to Short object array
  2. Use Arrays.asList method to convert Short[] into List and then iterate over them using streams.

See below sample code,

Short[] shortarray = {0,1,2};
List<Short> shortList1 = Arrays.asList(shortarray);
shortList1.stream().forEach(aShort -> {System.out.println(aShort);});`

Hope this helps.

Thanks Sandy

seenukarthi
  • 8,241
  • 10
  • 47
  • 68
Sandy
  • 16
  • 1
  • OP wants to convert `short[]` not `Short[]` – seenukarthi Feb 05 '20 at 09:51
  • Actually, `Arrays` class only considers int, long, double or any Object types as parameters at the moment. So simple answer is "not possible" at the moment as short as parameter to the stream method of Arrays class. Note: My opinion realted to Arrays.stream param support is valid until java 1.8 from my doc review. – Sandy Feb 05 '20 at 10:44