Skip to content
Related Articles

Related Articles

Merge Arrays into a New Object Array in Java

Improve Article
Save Article
  • Difficulty Level : Hard
  • Last Updated : 01 May, 2022
Improve Article
Save Article

Given two arrays of the same type, they need to be merged into a new object array. The task is to merge the two arrays of the same type into an object array such that the array elements maintain their original order in the newly merged array and the elements of the first array precede the elements of the second array in the merged object array.

This merging can be done in many Methods in Java, like Java8, System.arrraycopy(), and Java Collections.

Different Methods of merging Arrays into a New Object

  1. Using Stream API in Java 8 with using Stream.of(), flatMap() and toArray() methods
  2. Using concat() method Stream class 
  3. Using arraycopyOf() method of System class
  4. Using Java Collections for Java 8 and onwards
  5. Using Java Collections for Java 7   

Let us discuss these methods in detail which are as follows: 

Method 1: Using the Stream API in Java8 with using Stream.of(), flatMap() and toArray() methods 

Class hierarchy of Stream is as follows:

java.lang.Object
  ↳  java.util.stream
MethodAction Performed
of(T… values)Returns a sequential ordered stream whose elements are the specified values.
flatMap(Function<? super T,? extends Stream<? extends R%gt;> mapper)Returns a stream of objects after applying the mapping function on each element and then flattens the result.
toArray()Returns an array containing the elements of this stream.

Illustration:

Input :  a[] = {1, 2, 3}
         b[] = {4, 5, 6}
Output : {1, 2, 3, 4, 5, 6}

Output Explanation: Stream.of(a, b) gets the arrays and pipelines them into a single stream. Then the flatMap() method returns a stream of objects after applying the mapping function on each element of the Stream.of() and then flattens the result. At the end, toArray() converts the stream elements into an array and returns the formed array.

Example:

Java




// Java program to merge two arrays of
// same type into an Object array.
 
import java.util.stream.Stream;
import java.util.Arrays;
import java.io.*;
 
class GFG {
     
    public static <T> Object[] concatenate(T[] a, T[] b)
    {
        // Function to merge two arrays of
        // same type
        return Stream.of(a, b)
                    .flatMap(Stream::of)
                    .toArray();
 
        // Arrays::stream can also be used in place
        // of Stream::of in the flatMap() above.
    }
     
    public static void main (String[] args)
    {
        Integer[] a = new Integer[]{1,2,3};
        Integer[] b = new Integer[]{4,5,6};
     
        Object[] c = concatenate(a,b);
         
 
    System.out.println("Merged object array : "
                    + Arrays.toString(c));
    }
}

Output: 

Merged object array : [1, 2, 3, 4, 5, 6]

Method 2: Using Stream.concat(), Arrays.stream() and toArray() methods 

MethodAction Performed
concat(Stream<? extends T> a, Stream<? extends T> b)Creates a lazily concatenated stream whose elements are all the elements of the first stream followed by all the elements of the second stream.

Illustration:

Input : a[] = {1, 2, 3}
        b[] = {4, 5, 6}
Output : {1, 2, 3, 4, 5, 6}

Output Explanation: The Stream.concat() creates a merged stream in which the elements in the order in which they are in the parameter. Here the Stream.concat() creates a concatenated stream whose elements are all the elements of the stream converted from array ‘a’ followed by all the elements of the stream converted from array ‘b’. The concatenated stream is then converted to the array and returned.

Example:

Java




// Java program to merge two arrays of
// same type into an Object array.
 
import java.util.stream.Stream;
import java.util.Arrays;
import java.io.*;
 
class GFG {
     
    public static <T> Object[] concatenate(T[] a, T[] b)
    {
        // Function to merge two arrays of
        // same type
        return Stream.concat(Arrays.stream(a),
                            Arrays.stream(b))
                    .toArray();
    }
     
    public static void main (String[] args)
    {
        Integer[] a = new Integer[]{1,2,3};
        Integer[] b = new Integer[]{4,5,6};
     
        Object[] c = concatenate(a,b);
         
 
    System.out.println("Merged object array : "
                    + Arrays.toString(c));
    }
}

Output : 

Merged object array : [1, 2, 3, 4, 5, 6]

Method 3: Using arraycopy() Method of System class

The arraycopy() method of the System class has been present inside java.lang package copies a source array from a specific beginning position to the destination array from the mentioned position. No. of arguments to be copied are decided by len argument.

The components at source_Position to source_Position + length – 1 are copied to destination array from destination_Position to destination_Position + length – 1.

Syntax: Class Declaration

public final class System extends Object

Syntax: Method Declaration 

public static void arraycopy(Object source_arr, int sourcePos,
                            Object dest_arr, int destPos, int len)

Illustration:

Input : a[] = {1, 2, 3}
        b[] = {4, 5, 6}
Output : {1, 2, 3, 4, 5, 6}

Example:

Java




// Java program to merge two arrays of
// same type into an Object array.
 
import java.util.stream.Stream;
import java.util.Arrays;
import java.io.*;
 
class GFG {
     
    // Function to merge two arrays of same type
    public static <T> Object[] concatenate(T[] a, T[] b)
    {
        // Create an empty Object array of the combined
        // size of the array a and array b
        Object[] n=new Object[a.length + b.length];
         
        // Copy the array a into n
        System.arraycopy(a, 0, n, 0, a.length);
         
        // Copy the array b into n
        System.arraycopy(b, 0, n, a.length, b.length);
         
        return n;
    }
     
    public static void main (String[] args)
    {
        Integer[] a = new Integer[]{1,2,3};
        Integer[] b = new Integer[]{4,5,6};
     
        Object[] c = concatenate(a,b);
     
    System.out.println("Merged object array : "
                    + Arrays.toString(c));
    }
}

Output: 

Merged object array : [1, 2, 3, 4, 5, 6]

Method 4: Using Java Collections in Java 8

A Collection is a group of individual objects represented as a single unit. Java provides a Collection Framework that defines several classes and interfaces to represent a group of objects as a single unit.

Illustration: Using Java Collections for Java 8 Stream

Input : a[] = {1, 2, 3}
        b[] = {4, 5, 6}
Output : {1, 2, 3, 4, 5, 6}

Example:

Java




// Java program to merge two arrays of
// same type into an Object array.
 
import java.util.stream.*;
import java.util.Arrays;
import java.io.*;
 
class GFG {
 
    // Function to merge two arrays of same type
    public static <T> Object[] concatenate(T[] a, T[] b)
    {
         
        // Create an empty List of type Object
        List<Object> n = new ArrayList<>();
 
        // Add arrays to list
        Stream.of(a, b)
            .flatMap(Stream::of)
            .forEach(n::add);
         
        // Convert list to array and return
        return n.toArray();
    }
     
    public static void main (String[] args)
    {
        Integer[] a = new Integer[]{1,2,3};
        Integer[] b = new Integer[]{4,5,6};
     
        Object[] c = concatenate(a,b);
         
 
    System.out.println("Merged object array : "
                    + Arrays.toString(c));
    }
}

Output: 

Merged object array : [1, 2, 3, 4, 5, 6]

Method 5: Using Java Collections for Java 7 using Collections.addAll() 

Illustration:

Input : a[] = {1, 2, 3}
        b[] = {4, 5, 6}
Output : {1, 2, 3, 4, 5, 6}

Example:

Java




// Java program to merge two arrays of
// same type into an Object array.
 
import java.util.*;
import java.io.*;
 
class GFG {
 
    // Function to merge two arrays of same type
    public static <T> List<Object> concatenate(T[] a, T[] b)
    {
        // Create an empty List of type Object
        List<Object> n = new ArrayList<>();
         
        // Add the array a into n
        Collections.addAll(n, a);
         
        // Add the array b into n
        Collections.addAll(n, b);
         
        return n;
    }
     
    public static void main (String[] args)
    {
        Integer[] a = new Integer[]{1,2,3};
        Integer[] b = new Integer[]{4,5,6};
         
        List<Object> c = concatenate(a,b);
     
        System.out.println("Merged object array : "
                        + c);
    }
}

Output: 

Merged object array : [1, 2, 3, 4, 5, 6] 

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!