Merge (Combine) Two or More Arrays Into A Single Array In Java

By Saruque Ahamed Mollick

If you are looking for the easiest way to merge or concatenate multiple arrays into a single array using java, you are at the right place.
In this post, we gonna learn how to concatenate or merge multiple arrays and store that into a single array.
There may be an integer type array or might be a String type array, So we gonna demonstrate both of those.

We have a plenty of ways to do so. But as I said before we will use the easiest way to do so, that will be better understood and also reduce our effort to do so.
Here is the java code of merging arrays into a single array

import java.util.*;
import java.lang.*;

public class merge {

    
    public static void main(String args[]){
       Scanner scan=new Scanner(System.in);
          
         
      
          System.out.println("Enter the number of elements in first string array:");
          int n=scan.nextInt();
          String a[]= new String[n];
          for(int i=0;i<n;i++) {
          a[i]=scan.next();
          }
          System.out.println("Enter the number of elements in first string array:");
          int p=scan.nextInt();
          String b[]= new String[p];
          for(int i=0;i<p;i++) {
          b[i]=scan.next();
          }

          List<String> list = new ArrayList<String>(Arrays.asList(a));
          list.addAll(Arrays.asList(b));
          Object [] c = list.toArray();
          System.out.println("Its List Array:");
          System.out.println(Arrays.toString(c));
          
  
      
    
    
    

    }
}

Explanation

We took two String array here.

 String[] a

and

 String[] b

and the number of elements we can store in those String arrays are “n and p”

Now we started two loops for elements insertion in our Strings.
After insertion, we took new ArrayList

List list = new ArrayList(Arrays.asList(a));

Then We added b String to The first list which was holding the elements of a.
Created an object “c” to print those values easily.

Output:

Enter the number of elements in first string array:
3
Java
Php
C
Enter the number of elements in first string array:
2
Python
Ruby
Its List Array:
[Java, Php, C, Python, Ruby]

Leave a Reply

Your email address will not be published. Required fields are marked *