Merge Multiple Arrays in Java

In this post, we will discuss how to merge multiple arrays in Java into a single new array. The new array should maintain the original order of elements in individual arrays.

 

1. Java 8

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

 

1.1. Stream.of()

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

 

1.2. Stream.concat()

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

 

2. System.arraycopy()

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

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

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

 
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