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.importjava.util.stream.Stream;importjava.util.Arrays;importjava.io.*;classGFG {publicstatic<T> Object[] concatenate(T[] a, T[] b){// Function to merge two arrays of// same typereturnStream.of(a, b).flatMap(Stream::of).toArray();// Arrays::stream can also be used in place// of Stream::of in the flatMap() above.}publicstaticvoidmain (String[] args){Integer[] a =newInteger[]{1,2,3};Integer[] b =newInteger[]{4,5,6};Object[] c = concatenate(a,b);System.out.println("Merged object array : "+ Arrays.toString(c));}}chevron_rightfilter_noneOutput :
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.importjava.util.stream.Stream;importjava.util.Arrays;importjava.io.*;classGFG {publicstatic<T> Object[] concatenate(T[] a, T[] b){// Function to merge two arrays of// same typereturnStream.concat(Arrays.stream(a),Arrays.stream(b)).toArray();}publicstaticvoidmain (String[] args){Integer[] a =newInteger[]{1,2,3};Integer[] b =newInteger[]{4,5,6};Object[] c = concatenate(a,b);System.out.println("Merged object array : "+ Arrays.toString(c));}}chevron_rightfilter_noneOutput :
Merged object array : [1, 2, 3, 4, 5, 6]
- Using Stream.of(), flatMap() and toArray() methods:
- 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.importjava.util.stream.Stream;importjava.util.Arrays;importjava.io.*;classGFG {// Function to merge two arrays of same typepublicstatic<T> Object[] concatenate(T[] a, T[] b){// Create an empty Object array of the combined// size of the array a and array bObject[] n=newObject[a.length + b.length];// Copy the array a into nSystem.arraycopy(a,0, n,0, a.length);// Copy the array b into nSystem.arraycopy(b,0, n, a.length, b.length);returnn;}publicstaticvoidmain (String[] args){Integer[] a =newInteger[]{1,2,3};Integer[] b =newInteger[]{4,5,6};Object[] c = concatenate(a,b);System.out.println("Merged object array : "+ Arrays.toString(c));}}chevron_rightfilter_noneOutput:
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.importjava.util.stream.*;importjava.util.Arrays;importjava.io.*;classGFG {// Function to merge two arrays of same typepublicstatic<T> Object[] concatenate(T[] a, T[] b){// Create an empty List of type ObjectList<Object> n =newArrayList<>();// Add arrays to listStream.of(a, b).flatMap(Stream::of).forEach(n::add);// Convert list to array and returnreturnn.toArray();}publicstaticvoidmain (String[] args){Integer[] a =newInteger[]{1,2,3};Integer[] b =newInteger[]{4,5,6};Object[] c = concatenate(a,b);System.out.println("Merged object array : "+ Arrays.toString(c));}}chevron_rightfilter_noneOutput :
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.importjava.util.*;importjava.io.*;classGFG {// Function to merge two arrays of same typepublicstatic<T> List<Object> concatenate(T[] a, T[] b){// Create an empty List of type ObjectList<Object> n =newArrayList<>();// Add the array a into nCollections.addAll(n, a);// Add the array b into nCollections.addAll(n, b);returnn;}publicstaticvoidmain (String[] args){Integer[] a =newInteger[]{1,2,3};Integer[] b =newInteger[]{4,5,6};List<Object> c = concatenate(a,b);System.out.println("Merged object array : "+ c);}}chevron_rightfilter_noneOutput :
Merged object array : [1, 2, 3, 4, 5, 6]
- Using Java Collections for Java 8 Stream:
Recommended Posts:
- Java Program to Count Inversions in an array | Set 1 (Using Merge Sort)
- Is an array a primitive type or an object in Java?
- util.Arrays vs reflect.Array in Java with Examples
- Check whether array has all identical elements using Arrays.asList() and HashSet in Java
- Java.util.Arrays.parallelSetAll(), Arrays.setAll() in Java
- Merge two sets in Java
- StringJoiner merge() method in Java
- Java Program for Merge Sort
- Java program to merge two files into a third file
- Java Program for Iterative Merge Sort
- Java Program for Merge Sort for Linked Lists
- Java program to merge two files alternatively into third file
- Java program to merge contents of all the files in a directory
- Java program to merge two files alternatively into third file
- Object class in Java
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



