5

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.

akash
  • 22,664
  • 11
  • 59
  • 87
  • This has been answered before: http://stackoverflow.com/questions/27888429/how-can-i-create-a-stream-from-an-array – John Kuhns Jul 14 '15 at 13:40
  • 1
    @JohnKuhns the link you gave is fr a stream of objects. The OP wants a stream of primitive bytes. – JB Nizet Jul 14 '15 at 13:42

1 Answers1

7

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]);
Community
  • 1
  • 1
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255