[英]Convert Java java.util.Stream<Byte> to a byte array
I need to convert a stream (Java 8 stream, not InputStream) into a byte array.我需要将流(Java 8 流,而不是 InputStream)转换为字节数组。
I have tried using toArray
method of Stream
, but it doesn't accept byte[]::new
, as byte
is a primitive type.我曾尝试使用Stream
toArray
方法,但它不接受byte[]::new
,因为byte
是原始类型。
I also tried using toArray
method of IntStream
, but it doesn't accept arguments, it assumes you want to get int[]
back.我也尝试使用IntStream
toArray
方法,但它不接受参数,它假设您想要返回int[]
。
It's possible to convert a stream to a list or an array of boxed Byte
types, and then convert it to byte[]
, but I wonder if there is a better way.可以将流转换为列表或装箱Byte
类型的数组,然后将其转换为byte[]
,但我想知道是否有更好的方法。
Edit: Added code, if that helps understanding the question.编辑:添加代码,如果这有助于理解问题。 This doesn't compile, it's just pseudo-code.这不能编译,它只是伪代码。 If it helps, you can also consider IntStream
to be Stream<Byte>
, for my purposes it doesn't matter.如果有帮助,您也可以将IntStream
视为Stream<Byte>
,就我而言,这无关紧要。
byte[] getArray(IntStream stream) {
return stream.toArray();
}
I guess you can make byte[]
from the original stream's individual entries and then concatenate them in the end.我想您可以从原始流的各个条目中生成byte[]
,然后最后将它们连接起来。
static byte[] <T> toByteArray(Stream<T> stream, Function<T, byte[]> transform) {
Stream<byte[]> arrayStream = stream.map(transform);
arrayStream.collect(concatArrays);
}
However, the only implementation I can think of for a concatArrays
Collector would be:但是,我能想到的concatArrays
收集器的唯一实现是:
byte[]
containing the already collected data维护一个包含已收集数据的byte[]
System.arraycopy
to combine the arrays使用System.arraycopy
组合数组I'd expect you'd be better off with your "boxing to Byte
and then convert" in almost all cases.我希望您在几乎所有情况下都可以更好地使用“装箱到Byte
然后转换”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.