noMAD
noMAD

Reputation: 7844

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?

Upvotes: 2

Views: 1657

Answers (5)

Katona
Katona

Reputation: 4901

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()][]));

Upvotes: 5

Suresh Atta
Suresh Atta

Reputation: 121998

Try using ByteArrayOutputStream:

ByteArrayOutputStream out= new ByteArrayOutputStream( );

in loop

out.write(eachBytearray);

After loop

byte result[] = out.toByteArray( );

Upvotes: 11

arshajii
arshajii

Reputation: 129497

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.

Upvotes: 3

Joey
Joey

Reputation: 354396

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

Upvotes: 6

Xabster
Xabster

Reputation: 3720

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.

Upvotes: 0

Related Questions