What is the best way to convert a byte array to an IntStream?

徘徊边缘 提交于 2019-12-04 01:36:31
 byte[] bytes = {2, 6, -2, 1, 7};
 IntStream is = IntStream.range(0, bytes.length).map(i -> bytes[i]);

 ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);
 IntStream is2 = IntStream.generate(inputStream::read).limit(inputStream.available());
Sotirios Delimanolis
public static IntStream stream(byte[] bytes) {
    ByteBuffer buffer = ByteBuffer.wrap(bytes);
    return IntStream.generate(buffer::get).limit(buffer.remaining());
}

(This can easily be changed to take ints from the ByteBuffer, ie. 4 bytes to the int.)

For InputStream, if you want to consume it eagerly, just read it into a byte[] and use the above. If you want to consume it lazily, you could generate an infinite InputStream using InputStream::read as a Consumer (plus exception handling) and end it when you've reached the end of the stream.

Concerning

but neither is very functional due to the copying of the source

I don't see why that makes it non functional.

Also relevant

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!