简体   繁体   中英

List<byte[]> to single byte[]

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?

Try using ByteArrayOutputStream :

ByteArrayOutputStream out= new ByteArrayOutputStream( );

in loop

out.write(eachBytearray);

After loop

byte result[] = out.toByteArray( );

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.)

One-liner with Guava :

Bytes.concat(listOfByteArray.toArray(new byte[0][]));

or a little bit longer (spares one byte array allocation which occurs inside toArray in the shorter version)

Bytes.concat(listOfByteArray.toArray(new byte[listOfByteArray.size()][]));

This is easy enough to write from scratch:

int length = 0;
for (byte[] ba : listOfByteArrays) {
    length += ba.length
}


byte[] total = new byte[length];

int index = 0;
for (byte[] ba : listOfByteArrays) {
    for (byte b : ba) {
        total[index++] = b;
    }
}

total is the desired byte array.

I would loop the list and sum up the lengths of the arrays in the list. Create a byte[] that holds them all. Loop and copy with System.arrayCopy() into the appropriate indexes.

I don't think a 3rd party library is warranted for just such a thing as what you describe.

You seem to know how to code it, so I'll leave out example code.

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