OneBite.Dev - Coding blog in a bite size

merge multiple array in java

Code snippet on how to merge multiple array in java

public static <T> T[] merge(T[] ...arrays) {
    int size = 0;
    for (T[] array : arrays) {
        size += array.length;
    }
 
    T[] mergedArray = (T[]) java.lang.reflect.Array.newInstance(arrays[0].getClass().getComponentType(), size);
 
    int start = 0;
    for (T[] array : arrays) {
        System.arraycopy(array, 0, mergedArray, start, array.length);
        start += array.length;
    }
 
    return mergedArray;
}

This code is used to merge multiple arrays in Java. It takes in a variable number of arrays and returns a single array which contains the elements of all the given arrays in the same order. Firstly, it declares a variable “size” to store the total length of the merged array and loops through all the given arrays, adding their lengths to size. It then creates the merged array and assigns it to the “mergedArray” variable, using the getClass() method on the first array to get the component type of the array. Following this, it loops through the given arrays and uses the System.arraycopy() method to copy the elements of each array into the merged array, increasing the “start” variable each time by the length of the previous array. Finally, it returns the mergedArray.

java