2

I am trying to convert an array of bytes to a LinkedList<Byte>:

//data is of type byte[]
List<Byte> list = Arrays.stream(toObjects(data)).boxed().collect(Collectors.toList());

Byte[] toObjects(byte[] bytesPrim) {
    Byte[] bytes = new Byte[bytesPrim.length];
    Arrays.setAll(bytes, n -> bytesPrim[n]);

    return bytes;
}

The first line raises an error message saying:

The method boxed() is undefined for the type Stream<Byte>.

Any idea why am I getting this error message and how to circumvent this problem please?

Andrew Tobilko
  • 48,120
  • 14
  • 91
  • 142
ecdhe
  • 421
  • 4
  • 17
  • 3
    You can't box a stream that's already of boxed objects. =) – Louis Wasserman Nov 05 '17 at 21:21
  • @LouisWasserman Should I then kick out the call for boxed() method? – ecdhe Nov 05 '17 at 21:23
  • Well what do you expect it to do? Which method do you *expect* it to be calling? Note that your array type is already `Byte[]`, not `byte[]`. – Jon Skeet Nov 05 '17 at 21:24
  • Since your `toObjects` method already returns a `Byte[]`, there is no need for this stream operation at all. You can simply use `List list = Arrays.asList(toObjects(data));`. – Holger Nov 06 '17 at 10:42

3 Answers3

9

The method boxed() is designed only for streams of some primitive types (IntStream, DoubleStream, and LongStream) to box each primitive value of the stream into the corresponding wrapper class (Integer, Double, and Long respectively).

The expression Arrays.stream(toObjects(data)) returns a Stream<Byte> which is already boxed since there is no such thing as a ByteStream class.

Andrew Tobilko
  • 48,120
  • 14
  • 91
  • 142
0

First thing, you don't need the boxed() method there - you already do it yourself in toObjects() which converts it to Bytes.

Second thing, there's no such method for bytes. it exists for ints, doubles, but not bytes. see here

Nir Levy
  • 12,750
  • 3
  • 21
  • 38
0

For what you want to do you can directly use Arrays.asList(toObjects(data))since toObjects(data) is of type Byte[]. Alternatively if you really want to use Streams, then Stream.of(toObjects(data)).collect(Collectors.toList()) should do the trick.