简体   繁体   English

将字节数组转换为IntStream的最佳方法是什么?

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

Java 8 has java.util.stream.Stream and java.util.stream.IntStream types. Java 8具有java.util.stream.Stream和java.util.stream.IntStream类型。 java.util.Arrays has a method java.util.Arrays有一个方法

IntStream is = Arrays.stream(int[])

but no such method to make an IntStream from a byte[], short[] or char[], widening each element to an int. 但是没有这样的方法可以从byte [],short []或char []创建IntStream,将每个元素扩展为int。 Is there an idiomatic/preferred way to create an IntStream from a byte[], so I can operate on byte arrays in a functional manner? 是否有一种从byte []创建IntStream的惯用/首选方法,所以我可以以函数方式操作字节数组?

I can of course trivially convert the byte[] to int[] manually and use Arrays.stream(int[]), or use IntStream.Builder: 我当然可以手动将byte []转换为int []并使用Arrays.stream(int []),或者使用IntStream.Builder:

public static IntStream stream(byte[] bytes) {
   IntStream.Builder isb = IntStream.builder();
   for (byte b: bytes) 
       isb.add((int) b); 
   return isb.build();
}

but neither is very functional due to the copying of the source. 但是由于复制了源代码,它们都不是很有用。

There also does not seem to be an easy way to convert an InputStream (or in this case an ByteArrayInputStream) to an IntStream, which would be very useful for processing InputStream functionally. 似乎还没有一种简单的方法可以将InputStream(或者在本例中为ByteArrayInputStream)转换为IntStream,这对于在功能上处理InputStream非常有用。 (Glaring omission?) (明显遗漏?)

Is there a more functional way that is efficient and does not copy? 是否有更有效且不复制的功能方式?

 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());
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 int s from the ByteBuffer , ie. 4 bytes to the int .) (这很容易被改变为从ByteBuffer获取int ,即4个字节到int 。)

For InputStream , if you want to consume it eagerly, just read it into a byte[] and use the above. 对于InputStream ,如果你想急切地使用它,只需将其读入byte[]并使用上面的内容即可。 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. 如果你想懒惰地使用它,你可以使用InputStream::read作为Consumer (加上异常处理)生成一个无限的InputStream ,并在你到达流的末尾时结束它。

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 也相关

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM