Java Merge Array


 

Java Merge Array

In this section, you will learn how to merge array.

In this section, you will learn how to merge array.

Java Merge Array

You all are aware of Arrays, their structure, declaration, initialization, copying etc and used them in your applications. There is one thing important regarding arrays i.e merging of arrays - add two or more arrays into a single array. In this section, we are going to explain you this concept with an example.

In the given code, we have created a method 'merge()' where we have created a new array and copy the first array value to the new array and later append the new array with the values of other arrays. The parameter we have passed to the method merge(int []...arr) indicates that you can merge number of arrays. Now to use this method, we have created three arrays and allow the user to enter their values and call this method. This method merge all the values of arrays of any size and store them into another array.

Here is the code:

import java.util.*;

class MergeArray {
	public static int[] merge(int[]... arr) {
		int arrSize = 0;
		for (int[] array : arr) {
			arrSize += array.length;
		}
		int[] result = new int[arrSize];
		int j = 0;
		for (int[] array : arr) {
			for (int s : array) {
				result[j++] = s;
			}
		}
		return result;
	}

	public static void main(String[] args) {
		int[] array1 = new int[5];
		System.out.println("Enter 5 numbers");
		Scanner input = new Scanner(System.in);
		for (int i = 0; i < array1.length; i++) {
			array1[i] = input.nextInt();
		}
		int[] array2 = new int[3];
		System.out.println("Enter 3 numbers");
		for (int i = 0; i < array2.length; i++) {
			array2[i] = input.nextInt();
		}
		int[] array3 = new int[2];
		System.out.println("Enter 2 numbers");
		for (int i = 0; i < array3.length; i++) {
			array3[i] = input.nextInt();
		}
		int M[] = (int[]) merge(array1, array2, array3);
		System.out.println("Merged Array is: ");
		for (int i = 0; i < M.length; i++) {
			System.out.println(M[i]);
		}

	}
}

Output:

Enter 5 numbers
1
2
3
4
5
Enter 3 numbers
6
7
8
Enter 2 numbers
9
10
Merged Array is:
1
2
3
4
5
6
7
8
9
10

Ads