Java Code Example: join two arrays

Join two Arrays using arraycopy function of system class

In java there are several ways to join 2 arrays. The first way is to use the arraycopy function of the System class.

import java.util.Arrays;

class Cube {
    public static void main(String[] args) {
        int[] firstArray = { 1, 2, 3, 4, 5 };
        int[] secondArray = { 6, 7, 8, 9, 10 };
        int[] joinedArray = new int[firstArray.length + secondArray.length];

        /* Copies an array from the specified source array, beginning at the specified position, 
        to the specified position of the destination array. A subsequence of array components 
        are copied from the source array referenced by src to the destination array referenced by dest. 
        The number of components copied is equal to the length argument. The components at positions srcPos 
        through srcPos+length-1 in the source array are copied into positions destPos through destPos+length-1, 
        respectively, of the destination array. */
        System.arraycopy(firstArray, 0, joinedArray, 0, firstArray.length);
        System.arraycopy(secondArray, 0, joinedArray, firstArray.length, secondArray.length);

        System.out.println("First array: ");
        System.out.println(Arrays.toString(firstArray));
        System.out.println("Second array: ");
        System.out.println(Arrays.toString(secondArray));
        System.out.println("Joined array: ");
        System.out.println(Arrays.toString(joinedArray));
    }
}
Output
First array: 
[1, 2, 3, 4, 5]
Second array: 
[6, 7, 8, 9, 10]
Joined array: 
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Join two Arrays using streams

You can also use streams to concatenate 2 arrays. The concat() function of the Stream class takes care of concatenating the two arrays. The toArray() function returns an array containing the elements of the stream.

import java.util.stream.*;
import java.util.Arrays;

class Cube {
    public static void main(String[] args) {
        String[] firstArray = { "John", "Mike", "Sarah" };
        String[] secondArray = { "Lion", "Ari" };

        String[] joinedArray = Stream
                .concat(Arrays.stream(firstArray), Arrays.stream(secondArray))
                .toArray(String[]::new);

        System.out.println(Arrays.toString(joinedArray));
    }
}
Output
[John, Mike, Sarah, Lion, Ari]