Merge two arrays in Java

In this post, we will discuss how to merge 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. Java 8 Stream

We can use Stream API in Java 8 to merge two arrays. There are various ways to do that –

1.1. Stream.of()

 

1.2. Stream.concat()

 

2. System.arraycopy()

We start by allocating enough memory to the new array for accommodating 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. List

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

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

or

 

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.

 
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 🙂
 





Leave a Reply

Notify of
avatar
wpDiscuz