This post will discuss how to concatenate multiple arrays in Java into a single new array. The new array should maintain the original order of elements in individual arrays.

1. Using Java 8

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

Stream.of() method

We can obtain a stream consisting of all elements from every array using the static factory method Stream.of(). Once we have the stream, we can flatten it using the flatMap() method and then convert it back to an array using the toArray() method.

Stream.concat() method

The stream has a concat() method that takes two streams as input and creates a lazily concatenated stream out of them. We can use it to concatenate multiple arrays, as shown below:

2. Using System.arraycopy() method

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

 
Here’s a version that works with generics:

3. Using List

We can also use a list to concatenate multiple arrays in Java, as shown below. This approach is not recommended since it involves the creation of an intermediary list object.

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

That’s all about concatenating multiple arrays in Java.