- Example - Home
- Example - Environment
- Example - Strings
- Example - Arrays
- Example - Date & Time
- Example - Methods
- Example - Files
- Example - Directories
- Example - Exceptions
- Example - Data Structure
- Example - Collections
- Example - Networking
- Example - Threading
- Example - Applets
- Example - Simple GUI
- Example - JDBC
- Example - Regular Exp
- Example - Apache PDF Box
- Example - Apache POI PPT
- Example - Apache POI Excel
- Example - Apache POI Word
- Example - OpenCV
- Example - Apache Tika
- Example - iText
- Java Useful Resources
- Java - Quick Guide
- Java - Useful Resources
How to Merge Two Arrays in Java
Combining two arrays into a single array is known as merging two arrays. There are several methods for merging two arrays in Java, such as using the List.addAll() method or manually merging the arrays with a for loop. The following are the ways to merge two arrays
Merging two arrays using list.addall() method
Merging two arrays manually using a for-loop
Merging Arrays Using list.addall() Method
The Java ArrayList addAll(Collection<? extends E> c) method adds all elements from the specified collection to the end of this list, in the order they are returned by the Iterator of the specified collection.
Syntax
The following is the syntax for list.addall() method
public boolean addAll(Collection<? extends E> c)
Example
This example shows how to to merge two arrays in Java using list.addall() method
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Main {
public static void main(String args[]) {
String a[] = { "A", "E", "I" };
String b[] = { "O", "U" };
List list = new ArrayList(Arrays.asList(a));
list.addAll(Arrays.asList(b));
Object[] c = list.toArray();
System.out.println(Arrays.toString(c));
}
}
Output
[A, E, I, O, U]
Merging Arrays Manually Using for Loop
We will merge two arrays into a single array manually using a for loop. We will first copy elements from both arrays into a new array and then print the merged result. The for loop is used to repeat a block of code for a specified number of iterations.
Example
Following is an example of merging two arrays manually using a for loop
public class HelloWorld {
public static void main(String[] args) {
int[]a = {1,2,3,4};
int[]b = {4,16,1,2,3,22};
int[]c = new int[a.length+b.length];
int count = 0;
for(int i = 0; i < a.length; i++) {
c[i] = a[i];
count++;
}
for(int j = 0; j < b.length;j++) {
c[count++] = b[j];
}
for(int i = 0;i < c.length;i++) System.out.print(c[i]+" ");
}
}
Output
1,2,3,4,4,16,1,2,3,22 .