How to Merge Two Arrays in Java

06 May 2023 Balmiki Mandal 0 Core Java

How to Merge Two Arrays in Java?

Merging two arrays in Java is fairly straightforward and can be done in a few different ways. In this article, we will discuss the different methods for merging two arrays in Java.

Method 1: Iterative Approach

The iterative approach requires creating an entirely new array of the combined length of the two original arrays. We then loop through the elements of both arrays, adding each element to the newly created array. Below is some code that demonstrates the iterative approach.

int[] mergedArray = new int[array1.length + array2.length];
 
int i = 0;
for (int element : array1) {
    mergedArray[i] = element;
    i++;
}
 
for (int element : array2) {
    mergedArray[i] = element;
    i++;
}

Method 2: ArrayUtils Class

If you are using Apache Commons Lang library, you can use the ArrayUtils class to combine two arrays without directly manipulating the elements. The code below demonstrates how to use the ArrayUtils.addAll() method to merge two arrays.

int[] mergedArray = ArrayUtils.addAll(array1, array2);

Method 3: Java 8 Streams

In Java 8, you can use the Stream API to combine two arrays. The code below demonstrates how to use the Stream API to merge two arrays.

int[] mergedArray = Stream.of(array1, array2).flatMapToInt(Stream::of).toArray();

These are some of the methods for merging two arrays in Java. Depending on your needs, you may find one of these solutions more helpful than the others.

BY: Balmiki Mandal

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.