Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List<byte[]> to single byte[]

Tags:

java

List<byte[]> listOfByteArrays;

I want to get all the byte[] stored in this List to just one byte[] by appending all elements in the List. I know one way to do it and that is by using System.arrayCopy()but using that inside a loop is going to be a little messy (temporary variables and byte[] arrays). Tried finding a better way of doing it but couldn't. Any pointers? Any external API's I can use?

like image 729
noMAD Avatar asked Mar 27 '26 18:03

noMAD


2 Answers

Try using ByteArrayOutputStream:

ByteArrayOutputStream out= new ByteArrayOutputStream( );

in loop

out.write(eachBytearray);

After loop

byte result[] = out.toByteArray( );
like image 94
Suresh Atta Avatar answered Mar 30 '26 07:03

Suresh Atta


Why would you need temporary arrays?

  • Make one pass through your list, sum the lengths of the individual arrays.
  • Create a single array large enough to hold them all
  • Make a second pass through your list, using System.arraycopy to copy the array from the list to its appropriate place in the target array. (You would need to keep track of the offset in the target array, obviously.)
like image 23
Joey Avatar answered Mar 30 '26 09:03

Joey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!