Merge Arrays into an Object array in Java

In this post, we will discuss how to merge arrays of same type into single a new Object array using Java 8, System.arraycopy(), Java Collections, Guava and Apache Commons Lang.

The new array should maintain the original order of elements in individual arrays and all elements of the first array should precede all elements of the second array.


1. Java 8 Stream

The introduction of Stream API with Java 8 have made complex tasks very easy for Java programmers. There are several ways to merge arrays in Java 8:


1. Stream.of() + flatMap() + toArray()

We can also use Arrays::stream in place of Stream::of to flatten the stream as shown below:


2. Stream.concat() + + toArray()


2. System.arraycopy()

System.arraycopy() copies an array from the specified source array, beginning at the specified position, to the specified position of the destination array.

We can use it to merge arrays as shown below:

Here’s another version that also make use of Arrays.copyOf():


3. Java Collections

We can also make use Java Collections to merge two arrays by creating an intermediary Collection from elements of both arrays and then converting the Collection back to the Object array.

To illustate, consider below Java 8 code that uses List:

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


Since all above versions creates an intermediary List object, they should be avoided and System.arraycopy() should be used instead to ensure better performance.


4. Guava

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


5. Apache Commons Lang

Apache Commons Lang also provides ArrayUtils.addAll() that adds all the elements of the given arrays into a new array.

Thanks for reading.

Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂

Get great deals at Amazon

Leave a Reply

Notify of