How to Merge Two Arrays in Java?

Get Job-ready: Java Course with 45+ Real-time Projects! - Learn Java

A very common problem that is always asked in the world of data structure is merging two arrays, or concatenating two arrays. Thankfully java has various methods to solve this problem. In this article, we will take a look at all those problems individually and learn how to merge 2 arrays in java..

Understanding the Problem:

Basically, there are two arrays, say arr1[] and arr2[].
arr1[]={1,2,3,4,5}
arr2[]={6,7,8,9}
Now, our task is to merge these arrays into one array, say arr3[].
arr3[]={1,2,3,4,5,6,7,8,9}

merging two arrays in java

Ways to solve this problem:

In java, we have several ways to merge two arrays. The methods we are going to discuss here are:

  • Manual Method
  • arraycopy()
  • Java Collections
  • Java Stream API
  • Guava Library
  • Apache Commons Lang

We are going to discuss each method individually. As we go down the list, the programs get shorter and easier to implement.

1. Manual Method(Without using any Library functions):

In this process, we merge the two arrays manually without using any library functions. We iterate through the array to extract the values and copy them into another array.

Program to implement manual merging(Without using Library Functions):

package com.DataFlair.Merge;
class Manualmerge
{
    void main()
    {
        int arr1[] = {1,2,3,4,5};
        int arr2[] = {6,7,8,9};
        int arr1L = arr1.length;
        int arr2L =arr2.length;
        int arr3L = arr1L + arr2L;
        int[] arr3 =new int[arr3L];
        for (int i = 0; i < arr1L; i = i + 1) {
            arr3[i] = arr1[i];
        }
        for (int i = 0; i < arr2L; i = i + 1) {
            arr3[arr1L + i] = arr2[i];
        }
        for (int i = 0; i < arr3L; i =i + 1) {
            System.out.print(arr3[i]);
        }
    }
}

The output of the above Code:

123456789

2. Merge arrays Using arraycopy():

arraycopy is a library function present inside the utility package of java. Using arraycopy() we can reduce the program length by eliminating the loop completely. It also decreases time complexity.

Syntax:

System.arraycopy(source_array,Starting_Pos_source,destination_array, Starting_pos_dest,length);
Parameters:
  • source_array: Name of the source array
  • Starting_pos_source: The position of the source array to copy from
  • destination_array: Name of the destination array
  • Starting_pos_dest: The position of the destination array to copy to
  • length: The length up to which to copy. If not provided will copy the array till the end.

Program to implement array merging using arraycopy():

package com.DataFlair.Merge;
import java.util.Arrays;
public class arrcpy
{
    void main()
    {
        int arr1[] = {1,2,3,4,5};
        int arr2[] = {6,7,8,9};
        int arr1L = arr1.length;
        int arr2L =arr2.length;
        int arr3L = arr1L + arr2L;
        int[] arr3 =new int[arr3L];
        System.arraycopy(arr1, 0, arr3, 0, arr1L);
        System.arraycopy(arr2, 0, arr3, arr1L, arr2L);
        System.out.println(Arrays.toString(arr3));
    }
}

The output of the above program:

[1, 2, 3, 4, 5, 6, 7, 8, 9]

3. Merge arrays Using Collections in java:

This method basically involves the conversion of arrays to list view and back to arrays. So first, we convert the source arrays to lists and return them as list views. After that, we convert the list to an array and store them back to the destination array. All the functions used are part of the utility package of java.

Syntax:

asList(array_name): Used to return an array as a list.
addAll(List_name): Used to add one list to another.

Program implementing java collections:

package com.DataFlair.Merge;
import java.util.*;
public class collections
{
    public static void main(String args[])   
   {  
        String arr1[] = { "D", "A", "T", "A" };         
        String arr2[] = { "F", "L", "A", "I", "R" };                 
        List list = new ArrayList(Arrays.asList(arr1));
        list.addAll(Arrays.asList(arr2));     
        Object[] arr3 = list.toArray();  
        System.out.println(Arrays.toString(arr3));
   }
}

The output of the above code:

[D, A, T, A, F, L, A, I, R]

4. Merge arrays Using Java Stream API:

Java stream API is only available in Java 8 and above. It is present in the utility package. At first, we use the Stream.of() method to sequentially order the stream whose elements are the values. The flatMap() function returns a stream consisting of the results. After that, the toArray() function is used to return the array from the stream.

Syntax:
Stream.of():

static <T> Stream<T> of(T....values) 

Here T stands for the type of stream elements. The Stream.of() method accepts values.

flatMap():

<R> Stream<R> flatMap(Function<? Super T, ? extends Stream<? Extends R>> mapper)  

Here R stands for element type of new stream. The method accepts a mapper as a parameter.

toArray():

Object[] toArray()

Program implementing merging of array using Java Stream API:

package com.DataFlair.Merge;
import java.util.stream.Stream;   
import java.util.Arrays;   
import java.io.*;   
public class APIstream  
{
    public static <T> Object[] mergeArray(T[] arr1, T[] arr2)   
    {   
        return Stream.of(arr1, arr2).flatMap(Stream::of).toArray();   
    }   
    public static void main (String[] args)    
    {   
        Integer[] arr1 = new Integer[]{1,2,3,4,5};
        Integer[] arr2 = new Integer[]{6,7,8,9}; 
        Object[] arr3 = mergeArray(arr1,arr2); 
        System.out.println("Array after merging: "+ Arrays.toString(arr3));   
    }   
}  

The output of the above Program:

Array after merging: [1, 2, 3, 4, 5, 6, 7, 8, 9]

5. Merge arrays using Google’s Guava Library:

Guava Library is a library that was introduced by google. It contains many useful functions to make programs shorter and easier. One such function is the concat() function which basically concat two arrays into the third array easily. The syntax of guava libraries is very simple and easy to use. You can download the jar file and import it into the IDE to start using it.

Syntax:

concat(first_array,second_array,type)
Parameters:
  • first_array: The name of the first array whose elements are to be concatenated.
  • Second_array: The name of the second array whose elements are to be concatenated.
  • type: The component type of the returned array, example: string.class. In the case of primitive array type, it can be ignored.

Program to merge two arrays using Guava Library:

package com.DataFlair.Merge;
import com.google.common.primitives;
public class Guava
{
    void main()
    {
        int arr1[]={1,2,3,4,5};
        int arr2[]={6,7,8,9};
        int arr3[]=Ints.concat(arr1,arr2);
        for(int i : arr3)
        System.out.print(i);
    }
}

The Output of the above code:

123456789

6. Merge arrays Using Apache Commons Lang

Apache commons lang , according to me, is the simplest way to concatenate two arrays. It is similar to the Guava Library, for this we need to download the apache library from the apache website. The ArrayUtils.addAll() function adds both the arrays together into the resultant array. It is as simple as that.

Syntax:

addAll(array_first, array_second)
Parameters:
  • array_first: Name of first array.
  • array_second: Name of second array.

Program to merge two arrays using Apache Commons Lang:

package com.DataFlair.Merge;
import org.apache.commons.lang3.ArrayUtils;
import java.util.Arrays;
public class Apache
{
   public static void main(String[] args) 
   {
       String[] arr1 = new String[]{"D", "A", "T", "A"};
        String[] arr2 = new String[]{"F", "L", "A", "I", "R"};
        String[] arr3 = ArrayUtils.addAll(arr1, arr2);
        System.out.println(Arrays.toString(arr3));
        int [] intarr1 = new int[]{1,2,3,4,5};
        int[] intarr2 = new int[]{6,7,8,9};
        int[] intarr3 = ArrayUtils.addAll(intarr1, intarr2);
        System.out.println(Arrays.toString(intarr3));
    }
}

The output of the above Program:

DATAFLAIR
123456789

Now that we have seen how to merge an array, let us look at how to print an array in different ways.

Printing an Array in Java:

There are three methods to print an array.
1. Using For Loop.
2. Using For Each Loop.
3. Using Array.toString() method.

1. Using For loop

The most common way to print an array is to use a for loop to iterate through the array and print each index separately.

Syntax:

for(initialization; condition; increment/decrement)

Implementation of Array printing using for loop:

for (int index = 0; i < array_length; index =index + 1) 
{
   System.out.print(array[index]);
}

2. Using For each loop

We can use for each loop to loop through the indexes of an array and print them individually.
Syntax:

for(datatype : array_name)

Implementation of Array printing using for each loop:

for(int index : array)
   {
       System.out.print(index);
        }

3. Using Array.toString() method

We all know that the Array.toString() method converts an array to a string. So, we can simply convert the array to string and print the complete array. This will remove the loop completely and reduce time complexity.

Syntax:

Array.toString(array_name);

Printing the array using only one line of code:

System.out.println(Arrays.toString(array));

Conclusion

So, we can see that a single problem can be solved in innumerous ways. It is the duty of programmers to find a suitable solution to a problem that takes the minimum time complexity and the minimum space complexity. In this article, we talked about all the different ways in which we can merge two arrays. We can see how programming evolved through time and made programs shorter and more compact.

Your 15 seconds will encourage us to work even harder
Please share your happy experience on Google

courses

DataFlair Team

DataFlair Team is a group of passionate educators and industry experts dedicated to providing high-quality online learning resources on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. With years of experience in the field, the team aims to simplify complex topics and help learners advance their careers. At DataFlair, we believe in empowering students and professionals with the knowledge and skills needed to thrive in today’s fast-paced tech industry. Follow us for Free courses, expert insights, tutorials, and practical tips to boost your learning journey.

Leave a Reply

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