什么是字节数组转换为IntStream的最佳方式? [英] What is the best way to convert a byte array to an IntStream?

查看:197
本文介绍了什么是字节数组转换为IntStream的最佳方式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

的Java 8具有java.util.stream.Stream和java.util.stream.IntStream类型。 java.util.Arrays中有一个方法

  IntStream是= Arrays.stream(INT [])

但没有这样的方法,使从字节[]的IntStream,短期[]或烧焦[],每个元素拉大到一个int。是否有一个惯用/ preferred的方式来创建从字节[]的IntStream,这样我就可以在一个功能性的方式在字节数组操作?

我当然可以平凡转换的byte []手动INT []并使用Arrays.stream(INT []),或使用IntStream.Builder:

 公共静态IntStream流(字节[]字节){
   IntStream.Builder ISB = IntStream.builder();
   对于(BYTE B:字节)
       isb.add((INT)b)条;
   返回isb.build();
}

但也不是非常实用的,由于源的复制。

有也似乎不被转换成一个InputStream(或在这种情况下ByteArrayInputStream的)到IntStream,这将是处理功能的InputStream非常有用的一种简单的方法。 (明显的遗漏?)

是否有高效和更实用的方式不会复制?


解决方案

 字节[]字节= {2,6,-2,1,7};
 IntStream是= IntStream.range(0,bytes.length).MAP(I - >字节[I]); ByteArrayInputStream进行的InputStream =新ByteArrayInputStream进行(字节);
 IntStream IS2 = IntStream.generate(InputStream的阅读::).limit(inputStream.available());

Java 8 has java.util.stream.Stream and java.util.stream.IntStream types. java.util.Arrays has a method

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. Is there an idiomatic/preferred way to create an IntStream from a byte[], so I can operate on byte arrays in a functional manner?

I can of course trivially convert the byte[] to int[] manually and use Arrays.stream(int[]), or use 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. (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());

这篇关于什么是字节数组转换为IntStream的最佳方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆