How to Merge Two Arrays in Java

We hope you are enjoying reading our Java articles and are learning Java in an interesting way. In this article, we have come with a new tutorial that will teach you about merging two arrays in Java.

We must say that you are all now very familiar and comfortable with arrays in Java as we covered the concept of arrays in many articles.

In this article, we will learn how we can merge two different arrays in Java and form a resulting array without changing the sequence of its elements.

Merge two arrays in java

Merge two Arrays in Java

We know that an array is a contiguous memory location of elements that are of the same datatype. We can perform several operations on a single array but merging two arrays involves two different arrays.

Merging means concatenating elements of two arrays into a single array. The elements of the first array precede the elements of the second array.

For example:

Suppose there are three arrays named array1, array2 and array3. We will merge array1 and array2 into array3 as follows:

int array1[ ] = { 1, 2, 3, 4, 5 };                                                            // first array
int array2[ ] = { 6, 7, 8, 9, 10 };                                                         //second array
int array3[ ] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };                                  //third array(resultant array)

We can do this by manual method of combining two arrays or we can also use some predefined methods and libraries to accomplish this task. There are many ways to merge two arrays in Java.

Let’s discuss each of them with implementation.

Different Ways to Merge Arrays in Java

Different ways to Merge two arrays in java

Following are some different ways that we can use to merge two arrays in Java:

1. Using Conventional/manual method
2. Using arraycopy() method of Java
3. Using Java Collections
4. Using Java Stream API
5. Using ObjectArrays class of Guava library

1. Manual Method in Java

In this method, we do not use any predefined method for merging two arrays. We just take one array and then the second array. Then, we calculate the lengths of both the arrays and add the lengths.

We create a new array with the length as the sum of lengths of these two arrays. Now we just start adding the elements of each array in the resulting array. As a result of this method, we get a resulting array as the concatenation of two arrays.

Let’s see the code to understand this method:

Code to understand the manual method of merging two arrays in Java:

package com.techvidvan.mergearrays;
import java.util.Arrays;
public class ManualMethod {
  public static void main(String[] args) {
    //declaring two character arrays
    int[] array1 = {
      1,
      2,
      3,
      4
    };
    int[] array2 = {
      5,
      6,
      7,
      8
    };

    //Calculating sum of length of two arrays
    int length = array1.length + array2.length;

    System.out.println("First Array is: ");
    for (int i = 0; i < array1.length; i++) {
      System.out.print(" " + array1[i]);
    }
    System.out.println(" ");

    System.out.println("Second Array is: ");
    for (int i = 0; i < array2.length; i++) {
      System.out.print(" " + array2[i]);
    }

    //Creating a resulting array of the calculated length
    int[] result = new int[length];
    int position = 0;

    //for each loop to add array1 elements to the resulting array
    for (int element: array1) {
      result[position] = element;
      position++;
    }

    //for each loop to add array2 elements to the resulting array
    for (int element: array2) {
      result[position] = element;
      position++;
    }

    System.out.println("\nThe resulting array after merging two arrays is: ");
    System.out.println(Arrays.toString(result));
  }
}

Output

First Array is:
1 2 3 4
Second Array is:
5 6 7 8
The resulting array after merging two arrays is:
[1, 2, 3, 4, 5, 6, 7, 8]

2. arraycopy() Method in Java

Java arraycopy() is the method of the System class which belongs to the java.lang package. It copies an array from the specified source array to the specified position of the destination array.

The number of elements copied is equal to the length argument.

Syntax:

public static void arraycopy(Object source, int source_position, Object destination, int destination_position, int length)

Parameters of arraycopy() method:

  • source: It is a source array.
  • source_position: Starting point in the source array.
  • destination: It is a destination array.
  • destination_position: Starting position in the destination array.
  • length: The number of array elements to be copied

Example of arraycopy() method:

In the following example, we have created two integer arrays array1 and array2. To merge two arrays, firstly we find the length of each array. We store the length of array1 in length1 variable and length of array2 in length2 variable.

After that, we create a new integer array result which stores the sum of length of both arrays. Now, we copy each element of both arrays to the result array by using the arraycopy() method.

package com.techvidvan.mergearrays;
import java.util.Arrays;
public class ArrayCopyMethod {
  public static void main(String[] args) {
    int[] array1 = {
      1,
      2,
      3,
      4
    };
    int[] array2 = {
      5,
      6,
      7,
      8
    };

    System.out.println("First Array is: ");
    for (int i = 0; i < array1.length; i++) {
      System.out.print(" " + array1[i]);
    }
    System.out.println(" ");

    System.out.println("Second Array is: ");
    for (int i = 0; i < array2.length; i++) {
      System.out.print(" " + array2[i]);
    }
    //Calculating length of each array
    int length1 = array1.length;
    int length2 = array2.length;
    int[] result = new int[length1 + length2];

    //Using arraycopy method to merge two arrays
    System.arraycopy(array1, 0, result, 0, length1);
    System.arraycopy(array2, 0, result, length1, length2);

    System.out.println("\nThe resulting array after merging two arrays is: ");
    System.out.println(Arrays.toString(result));
  }
}

Output: First Array is: 1 2 3 4
Second Array is: 5 6 7 8
The resulting array after merging two arrays is: [1, 2, 3, 4, 5, 6, 7, 8]

Output

First Array is:
1 2 3 4
Second Array is:
5 6 7 8
The resulting array after merging two arrays is:
[1, 2, 3, 4, 5, 6, 7, 8]

3. Using Java Collections

We know that a Collection in Java is a group of different objects collected into a single unit. The Collection framework in Java contains many classes and interfaces to group many objects into a single unit.

So, we can also use them to merge two arrays into a single array.

Code to merge two arrays using Collections in Java:

package com.techvidvan.mergearrays;
import java.util. * ;
public class MergeArrayExample4 {
  public static void main(String args[]) {
    String str1[] = {
      "T",
      "E",
      "C",
      "H"
    }; //source array  
    String str2[] = {
      "V",
      "I",
      "D",
      "V",
      "A",
      "N"
    }; //destination array  
    System.out.print("The first array is:");
    for (int i = 0; i < str1.length; i++) {
      System.out.print(" " + str1[i]);
    }
    System.out.print("\nThe second array is:");
    for (int i = 0; i < str2.length; i++) {
      System.out.print(" " + str2[i]);
    }
    //returns a list view of an array  
    List list = new ArrayList(Arrays.asList(str1));

    //returns a list view of str2 and adds all elements of str2 into list  
    list.addAll(Arrays.asList(str2));

    //converting list to array  
    Object[] str3 = list.toArray();
    System.out.print("\nThe merged array is: ");
    System.out.println(Arrays.toString(str3));
    //prints the resultant array  
  }
}

Output:

The first array is: T E C H
The second array is: V I D V A N
The merged array is: [T, E, C, H, V, I, D, V, A, N]

4. Java Stream API

If you have Java 8 installed in your system, then you can use this feature to merge two arrays. The Stream API(Application Programming Interface) provides many methods that are used to merge two arrays in Java.

This API is present in the java.util.stream package of Java. It also makes use of collections but using Stream API you can work with collections in Java 8 to merge 2 arrays.

Code to understand the Java Collection for Java 8 Stream Of merging two arrays in Java:

package com.techvidvan.mergearrays;
import java.util. * ;
import java.util.stream.Stream;
import java.util.Arrays;
import java.io. * ;

public class StreamDemo {
  // To merge our two arrays we declare the following Function.
  public static < Merge > Object[] merging(Merge[] array1, Merge[] array2) {
    // Creating a List of type Object for merge our two arrays 
    List < Object > array3 = new ArrayList < >();

    // Adding the array one-by-one into the list
    Stream.of(array1, array2).flatMap(Stream::of).forEach(array3::add);

    // Converting the list to array and returning the array to the main method 
    return array3.toArray();
  }

  public static void main(String[] args) {
    // Declaring an array that we have to merge
    Integer[] array1 = new Integer[] {
      1,
      2,
      3,
      4,
      5
    };

    // Declaring another array that we have to merge
    Integer[] array2 = new Integer[] {
      6,
      7,
      8,
      9,
      10
    };

    // creating object to call the merge method
    Object[] array3 = merging(array1, array2);

    System.out.println("Merged array after merging our two array: " + Arrays.toString(array3));
  }
}

Output:

Merged array after merging our two array: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

5. Using Guava Library in Java

The Guava library of Java contains an ObjectArrays class that contains a concat() method to merge two arrays and returns the concatenated contents of two arrays.

3 Parameters of Java concat() method:

  • first – the first array of elements to concatenate
  • second – the second array of elements to concatenate
  • type – the component type of the returned array

Code snippet to understand concat() method:

// Function to merge two arrays in Java
public static String[] concatenate(String[] first, String[] second) {
  return ObjectArrays.concat(first, second, String.class);
}

Conclusion

In this article, we learned how to merge two arrays in Java. Merging two arrays means concatenating elements of two arrays into a single array.

There may be many situations when you need to merge two arrays and perform the operations on the resulting merged array, in this article, we discussed each way of merging two arrays in Java with examples.

You can use any of them according to your comfort.

To master Java, stay with TechVidvan!!!

Your opinion matters
Please write your valuable feedback about TechVidvan on Google | Facebook


Leave a Reply

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