Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No method to get stream of byte array [duplicate]

Tags:

java

java-8

I want to get stream of byte array but I came to know that Arrays does not have method to get stream of byte array.

byte[] byteArr = new byte[100];
Arrays.stream(byteArr);//Compile time error

My questions,

  • Why this feature is not supported ?
  • How can I get Stream of byte array ?

NOTE : I know I can use Byte[] instead of byte[] but that does not answer my question.

like image 752
akash Avatar asked Jul 14 '15 13:07

akash


Video Answer


1 Answers

There are only 3 types of primitive streams: IntStream, LongStream and DoubleStream.

So, the closest you can have is an IntStream, where each byte in your array is promoted to an int.

AFAIK, the simplest way to build one from a byte array is

    IntStream.Builder builder = IntStream.builder();
    for (byte b : byteArray) {
        builder.accept(b);
    }
    IntStream stream = builder.build();

EDIT: assylias suggests another, shorter way:

IntStream stream = IntStream.range(0, byteArr.length)
                            .map(i -> byteArray[i]);
like image 85
JB Nizet Avatar answered Oct 11 '22 14:10

JB Nizet