![]() |
VOOZH | about |
In Java, merging two arrays is a good programming question. We have given two arrays, and our task is to merge them, and after merging, we need to put the result back into another array. In this article, we are going to discuss different ways we can use to merge two arrays in Java.
Let's now see the real implementation of this for better understanding.
Example: In the below example, we are merging two arrays into a new array.
[10, 20, 30, 40, 50, 60, 70, 80]
Explanation: In the above example, we are using in-built System.arraycopy() method to merge two arrays. Here, we are initalizing two arrays arr1 and arr2 and inserting values in them and then we are calculating the length. Then we create another array which will hold the merged result and the last step is to use System.arraycopy() to merge both arrays into the third array.
Now, we are going to discuss some methods to merge two arrays which are listed below:
1. Without Using Pre-Defined Function: This method is used for merging two arrays manually. It gives us full control over the process and does not rely on built-in functions.
Example:
[10, 20, 30, 40, 50, 60, 70, 80]
Explanation: In this example, we are initalizing two arrays, arr1 and arr2 and then we are creating another array c which will store the merged result. The first loop copies elements from arr1 to c and the second loop copies elements from arr2 to c and in the end we are printing the merged array.
2. Using Java Streams: This method is used to merge two arrays with the help of Java Streams.
Example:
[10, 20, 30, 40, 50, 60, 70, 80]
Explanation: Here, we are merging two arrays with the help of IntStream.concat() method and then the result is converted back into an array. We are using mergeArraysUsingStreams method because it combines the two arrays and returns the merged array as an int[].
3. Using ArrayList: This method uses ArrayList to merge two arrays. An ArrayList is a linear data structure in Java which can automatically increases its size when needed.
Example:
[10, 20, 30, 40, 50, 60, 70, 80]
Explanation: Here, ArrayList is holding all the elements from the two merged arrays. Then for-each loop is used to iterate over the elements of an array and then we are converting the ArrayList back into a regular array and in the end we are printing the merged array.