This post will discuss concatenating two arrays in Java into a new array. The new array should maintain the original order of elements in individual arrays, and all elements in the first array should precede all elements of the second array.

1. Using Java 8 Stream

We can use Stream in Java 8 and above to concatenate two arrays. There are various ways to do that:

Stream.of() method

Stream.concat() method

2. Using System.arraycopy() method

We start by allocating enough memory to the new array to accommodate all the elements present in both arrays. Then we use System.arraycopy() to copy given arrays into the new array, as shown below:

 
Here’s a version that works with generics:

 
Here’s another generic version that uses Arrays.copyOf() along with System.arraycopy():

3. Using List

We can also use a list to concatenate two arrays, as shown below. This approach is not suggested over Java 8, and the System.arraycopy() method discussed earlier since it involves creating an intermediary list object.

 
For Java 7 and before, we can use Collections.addAll() method:

or

4. Using Guava Library

Guava library provides ObjectArrays class that has the concat() method, which returns a new array of the specified type containing concatenated contents of two arrays.

That’s all about concatenating two arrays in Java.