0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Java】Byte配列を無限に連結したい

Last updated at Posted at 2021-10-19

やりたいこと

JavaでByte配列を扱う中で配列を連結させたい場面がありました。
しかも、ときには2つ、ときには3つ、、というように。
Kotlin版はこちら 【Kotlin】ByteArrayを無限に連結したい

追記

コメントいただきましたが、Arrays.stream()を使うとよりスッキリ実現できます。(ありがとうございます。)

private static byte[] concatByteArrays(byte[]... arrays) {
    return Arrays.stream(arrays)
        .collect(ByteArrayOutputStream::new,
            (bos, bytes) -> bos.writeBytes(bytes),
            (left, right) -> left.writeBytes(right.toByteArray()))
        .toByteArray();
}

結果

Byte配列はByteBufferで扱い、引数は可変長引数で受け取ることで対応しています。

class ConcatArrayTest
{
    private static byte[] concatByteArrays(byte[]... arrays) {
        if (arrays.length <= 1) {
            return arrays[0];
        }
        int length = 0;
        for (byte[] array : arrays) {
            length += array.length;
        }
        ByteBuffer buffer = ByteBuffer.allocate(length);
        for (byte[] array : arrays) {
            buffer.put(array);
        }
        return buffer.array();
    }
    
    public static void main (String[] args) throws java.lang.Exception
    {
        byte[] array1 = {1, 2};
        byte[] array2 = {3, 4, 5};
        byte[] array3 = {6, 7, 8, 9};
        
        byte[] concatArray1 = concatByteArrays(array1);
        System.out.println("array1 : " + Arrays.toString(concatArray1));
        byte[] concatArray2 = concatByteArrays(array1, array2);
        System.out.println("array2 : " + Arrays.toString(concatArray2));
        byte[] concatArray3 = concatByteArrays(array1, array2, array3);
        System.out.println("array3 : " + Arrays.toString(concatArray3));
    }
}

Output

array1 : [1, 2]
array2 : [1, 2, 3, 4, 5]
array3 : [1, 2, 3, 4, 5, 6, 7, 8, 9]
0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?