简体   繁体   中英

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.

I have tried using toArray method of Stream , but it doesn't accept byte[]::new , as byte is a primitive type.

I also tried using toArray method of IntStream , but it doesn't accept arguments, it assumes you want to get int[] back.

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.

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.

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.

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:

  • maintain a byte[] containing the already collected data
  • for each entry of the Stream, expand it to accomodate the new entry
  • use System.arraycopy to combine the arrays

I'd expect you'd be better off with your "boxing to Byte and then convert" in almost all cases.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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