Merge Arrays into a New Object Array in Java
Last Updated :
01 Mar, 2023
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.arraycopy(), and Java Collections.
Different Methods of merging Arrays into a New Object
- Using Stream API in Java 8 with using Stream.of(), flatMap() and toArray() methods
- Using concat() method Stream class
- Using arraycopyOf() method of System class
- Using Java Collections for Java 8 and onwards
- 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
| Method |
Action 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
import java.util.stream.Stream;
import java.util.Arrays;
import java.io.*;
class GFG {
public static <T> Object[] concatenate(T[] a, T[] b)
{
return Stream.of(a, b)
.flatMap(Stream::of)
.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 2: Using Stream.concat(), Arrays.stream() and toArray() methods
| Method |
Action 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
import java.util.stream.Stream;
import java.util.Arrays;
import java.io.*;
class GFG {
public static <T> Object[] concatenate(T[] a, T[] b)
{
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
import java.util.stream.Stream;
import java.util.Arrays;
import java.io.*;
class GFG {
public static <T> Object[] concatenate(T[] a, T[] b)
{
Object[] n=new Object[a.length + b.length];
System.arraycopy(a, 0, n, 0, a.length);
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
import java.util.stream.*;
import java.util.Arrays;
import java.io.*;
class GFG {
public static <T> Object[] concatenate(T[] a, T[] b)
{
List<Object> n = new ArrayList<>();
Stream.of(a, b)
.flatMap(Stream::of)
.forEach(n::add);
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
import java.util.*;
import java.io.*;
class GFG {
public static <T> List<Object> concatenate(T[] a, T[] b)
{
List<Object> n = new ArrayList<>();
Collections.addAll(n, a);
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]
Similar Reads
Java Tutorial
Java is a high-level, object-oriented programming language used to build applications across platformsâfrom web and mobile apps to enterprise software. It is known for its Write Once, Run Anywhere capability, meaning code written in Java can run on any device that supports the Java Virtual Machine (
10 min read
Java Interview Questions and Answers
Java is one of the most popular programming languages in the world, known for its versatility, portability, and wide range of applications. Java is the most used language in top companies such as Uber, Airbnb, Google, Netflix, Instagram, Spotify, Amazon, and many more because of its features and per
15+ min read
Arrays in Java
Arrays in Java are one of the most fundamental data structures that allow us to store multiple values of the same type in a single variable. They are useful for storing and managing collections of data. Arrays in Java are objects, which makes them work differently from arrays in C/C++ in terms of me
15+ min read
Java OOP(Object Oriented Programming) Concepts
Java Object-Oriented Programming (OOPs) is a fundamental concept in Java that every developer must understand. It allows developers to structure code using classes and objects, making it more modular, reusable, and scalable. The core idea of OOPs is to bind data and the functions that operate on it,
13 min read
Collections in Java
Any group of individual objects that are represented as a single unit is known as a Java Collection of Objects. In Java, a separate framework named the "Collection Framework" has been defined in JDK 1.2 which holds all the Java Collection Classes and Interface in it. In Java, the Collection interfac
15+ min read
Inheritance in Java
Java Inheritance is a fundamental concept in OOP(Object-Oriented Programming). It is the mechanism in Java by which one class is allowed to inherit the features(fields and methods) of another class. In Java, Inheritance means creating new classes based on existing ones. A class that inherits from an
14 min read
Java Programs - Java Programming Examples
In this article, we will learn and prepare for Interviews using Java Programming Examples. From basic Java programs like the Fibonacci series, Prime numbers, Factorial numbers, and Palindrome numbers to advanced Java programs. Java is one of the most popular programming languages today because of it
8 min read
HashMap in Java
In Java, HashMap is part of the Java Collections Framework and is found in the java.util package. It provides the basic implementation of the Map interface in Java. HashMap stores data in (key, value) pairs. Each key is associated with a value, and you can access the value by using the corresponding
15+ min read
Java Exception Handling
Exception handling in Java allows developers to manage runtime errors effectively by using mechanisms like try-catch block, finally block, throwing Exceptions, Custom Exception handling, etc. An Exception is an unwanted or unexpected event that occurs during the execution of a program (i.e., at runt
10 min read
ArrayList in Java
Java ArrayList is a part of the collections framework and it is a class of java.util package. It provides us with dynamic-sized arrays in Java. The main advantage of ArrayList is that, unlike normal arrays, we don't need to mention the size when creating ArrayList. It automatically adjusts its capac
10 min read