When I use Java 8 Stream.of primitive type, the result is confused

    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?

+4
source share
2 answers

Stream.ofaccepts objects only as their arguments. A byteis not an object, but an array byte. If ais an array of byte, then it Stream.of(a)can only mean "the stream of this one object, which is an array."

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

There is information on how you can pass an array of bytes: Does Java 8 have a ByteStream class?

+7

, , , ByteStream. byte[] int[], :

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

Stream<byte[]>, , static<T> Stream<T> of(T t), static<T> Stream<T> of(T... values) Stream, , , type .

System.out.println(Stream.of(b).count()); b , static<T> Stream<T> of(T... values) Stream<Byte> .

+3

Source: https://habr.com/ru/post/1658793/


All Articles