Merge arrays into a new object array in Java

Merge arrays into a new object array in Java

Merge arrays into a new object array in Java

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 precedes the elements of the second array in the merged object array.

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

Java 8: In Java8 this can be done using the Stream API.
Using Stream.of(), flatMap() and toArray() methods:

Class hierarchy of Stream :
java.lang.Object
↳ java.util.stream
Method description

Modifier and Type Method Description
static <T> Stream<T> of(T… values) Returns a sequential ordered stream whose elements are the specified values.
<R> Stream<R> flatMap(Function<? super T,? extends Stream<? extends R%gt;> mapper) Returns a stream of object after applying mapping function on each element and then flattens the result.
Object[] toArray() Returns an array containing the elements of this stream.
Examples:

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

Explanation:
Stream.of(a, b) gets the arrays and pipeline them into a single stream. Then the flatMap() method returns a stream of object after applying 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 return the formed array.

// 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 P_AI {

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]

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

Modifier and Type Method Description
static <T> Stream<T> 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.
Examples:

Input : a[] = {1, 2, 3}
b[] = {4, 5, 6}
Output : {1, 2, 3, 4, 5, 6}
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 stream converted from array ‘a’ followed by all the elements of stream converted from array ‘b’. The concatenated stream is then converted to the array and returned.

// 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 P_AI {

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]

System.arraycopy(): The java.lang.System.arraycopy() method 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.

Class Declaration:

public final class System extends Object
Syntax:

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

Parameters :

  • source_arr : array to be copied from
  • sourcePos : starting position in source array from where to copy
  • dest_arr : array to be copied in
  • destPos : starting position in destination array, where to copy in
  • len : total no. of components to be copied.
    Examples:

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

// 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 P_AI {

// 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]

Java Collections: A Collection is a group of individual objects represented as a single unit. Java provides Collection Framework which defines several classes and interfaces to represent a group of objects as a single unit.
Using Java Collections for Java 8 Stream:
Examples:
Input : a[] = {1, 2, 3}
b[] = {4, 5, 6}
Output : {1, 2, 3, 4, 5, 6}

// 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 P_AI {

// 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]

Using Java Collections for Java 7 using Collections.addAll():
Examples:
Input : a[] = {1, 2, 3}
b[] = {4, 5, 6}
Output : {1, 2, 3, 4, 5, 6}

// Java program to merge two arrays of
// same type into an Object array.

import java.util.*;
import java.io.*;

class P_AI {

// 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]

Different ways to create objects in Java (Prev Lesson)
(Next Lesson) Types of Exception in Java with Examples