4
    byte[] a = {1,2,3};
    System.out.println(Stream.of(a).count());

    Byte[] b = {1,2,3};
    System.out.println(Stream.of(b).count());

the result is 1 and 3, why?

Alexis C.
  • 91,686
  • 21
  • 171
  • 177
yi jiang
  • 216
  • 1
  • 13
  • One way to create a stream of Bytes can be found [here](https://stackoverflow.com/questions/32459683/in-java-8-is-there-a-bytestream-class/58520704#58520704) – Kaplan Oct 23 '19 at 10:29

2 Answers2

8

Stream.of only accepts Objects as its arguments. A byte isn't an Object, but a byte array is. If a is an array of byte, then Stream.of(a) can only mean "stream of this one object, which is an array".

If you have a Byte[] array, then each element of the array is an object, so the compiler can guess that's what you mean.

There is information here about how you can stream a byte array: In Java 8, is there a ByteStream class?

Community
  • 1
  • 1
khelwood
  • 55,782
  • 14
  • 81
  • 108
3

For primitive arrays you should be using primitive streams, but unfortunately there is no ByteStream. If you change your byte[] to int[], you could write :

int[] a = {1,2,3};
System.out.println(IntStream.of(a).count());

Otherwise you get a Stream<byte[]> whose single element is the input array, since both static<T> Stream<T> of(T t) and static<T> Stream<T> of(T... values) expect a reference type as the Stream element, so when you pass a primitive array, the only available reference type is the array itself.

In your System.out.println(Stream.of(b).count()); case, b is an array of reference types, so static<T> Stream<T> of(T... values) is used to produce a Stream<Byte> of 3 elements.

Eran
  • 387,369
  • 54
  • 702
  • 768