How to Merge Two Arrays in Java?12 Feb 2025 | 7 min read Merging two arrays in Java is a fundamental operation that is often required in various applications. It can be done in several ways depending on the specific requirements and constraints of the problem at hand. Merging two arrays in Java is similar to concatenate or combine two arrays in a single array object. We have to merge two arrays such that the array elements maintain their original order in the newly merged array. The elements of the first array precede the elements of the second array in the newly merged array. For example: Use CasesMerging two arrays in Java is a common task in various scenarios, including: Data Processing: When working with datasets stored in multiple arrays, merging them allows for streamlined data processing and analysis. For example, merging arrays of student names and corresponding grades facilitates calculating averages or sorting based on grades. User Input: In applications where users can input data in batches or sections, merging arrays enables combining multiple input arrays into a single dataset for further processing or storage. Database Operations: When retrieving data from a database, results may be stored in separate arrays representing different columns or attributes. Merging these arrays consolidates the data for presentation or manipulation. Sorting and Searching: Merging arrays is often a prerequisite for sorting or searching algorithms. Before applying these operations, it's essential to merge smaller arrays into larger ones to ensure proper sorting or searching across the entire dataset. Resource Management: In resource-constrained environments, merging arrays conserves memory by minimizing the number of separate arrays, leading to more efficient resource utilization. Ways to Merge Two ArraysThere are the following ways to merge two arrays:
Java System.arraycopy() MethodThe System.arraycopy() method in Java is a powerful and efficient way to copy elements from one array to another. It is used to perform a shallow copy of array elements. It can be employed to copy elements from one array to another, to copy a subarray, or to shift elements within an array. The number of elements copied is equal to the length argument. Syntax: Parameters
It throws NullPointerException if the source or destination array is null. It also throws ArrayIndexOutOfBoundsException if:
Example of arraycopy() Method In the following example, we have created two integer arrays firstArray and secondArray. In order to merge two arrays, we find its length and stored in fal and sal variable respectively. After that, we create a new integer array result which stores the sum of length of both arrays. Now, copy each elements of both arrays to the result array by using arraycopy() function. MergeArrayExample1.java Output: [23, 45, 12, 78, 4, 90, 1, 77, 11, 45, 88, 32, 56, 3] Let's see another example in which we have specified soure_array, destination, dest_position, source position, and length. We can merge array according to the specified positions and length. Example MergeArrayExample2.java Output: source_array: 11 22 33 44 55 98 76 54 60 sourcePos: 2 dest_array: 66 77 88 99 22 67 21 90 80 70 destPos: 4 len: 3 Resultant array: 66 77 88 99 33 44 55 90 80 70 Without using arraycopy() methodThe System.arraycopy() method is an efficient native method in Java for copying elements between arrays. It handles type safety, bounds checking, and performs the copy operation much faster than a manual loop due to its low-level implementation. Without using System.arraycopy(), one must manually loop through the source array to copy elements to the destination array, which is less efficient and more error-prone, especially for large arrays. Here's a simple example of manually copying elements using loops: Example of Merging Two Arrays In the following example, we have initialized two arrays firstArray and secondArray of integer type. Manually copy the each element of both arrays to mergedArray and convert that array into String by using the toString() method of Array class. MergeArrayExample3.java Output: [56, 78, 90, 32, 67, 12, 11, 14, 9, 5, 2, 23, 15] Using CollectionsUsing Java Collections Framework provides a flexible and efficient way to manage groups of objects. Collections, such as ArrayList, LinkedList, HashSet, and HashMap, offer dynamic data structures that can grow or shrink as needed, unlike fixed-size arrays. They come with built-in methods for adding, removing, and manipulating elements, making tasks like sorting, searching, and merging simpler and more efficient. For example, ArrayList allows dynamic resizing and provides methods like add(), remove(), and get(). Collections also support generics, ensuring type safety at compile-time. Merging two collections can be easily done using methods like addAll(): Example of Merging Two Arrays in Java In the following example, we have initialized two arrays str1 and str2 of String type. After that we have created a list view of str1 by using the Arrays.asList() method. Now we have created the list view of str2 and added all the elements of str2 into the list. Again perform conversion from list to array and store the resultant array into str3 variable. MergeArrayExample4.java Output: [A, E, I, O, U] Java Stream APIStream.of() Method The Stream.of() method of Stream interface returns a sequential ordered stream whose elements are the values. Syntax Where, T is the type of stream elements. The method accepts values (elements of the new stream). Stream.flatMap() Method The Stream.flatMap() method is the method of Stream interface. It returns a stream consisting of the result. Syntax Where R is the element type of new stream. The method accepts a mapper (a function to apply to each element which produces a stream of new values) as a parameter. Stream.toArray() Method The Stream.toArray() method of Stream interface returns an array containing the elements of the stream. Syntax Example of Merging Two Arrays Using Stream API MergeArrayExample5.java Output: Merged array: [13, 12, 11, 6, 9, 3, 78, 34, 56, 67, 2, 11, 7] Best Practices
ConclusionThe System.arraycopy() method is a versatile and efficient tool for copying array elements in Java. By understanding its parameters, handling exceptions, and knowing when to use it, we can effectively manage array manipulations in your Java applications. Whether merging arrays, copying subarrays, or shifting elements, System.arraycopy() provides a robust solution for these tasks. Next TopicJava Tutorial |
Like other programming language, Java also has some constants. In the ious section, we have discussed, Java constants, how to declare constants. So, in this section, we will discuss the only types of constants in Java and how to use it. Constants It is the value that cannot...
7 min read
In this section, we will see how one can compute the maximum rectangular area in the histogram. What is maximum rectangular area in the histogram? The maximum rectangle that has to be created should be made of continuous bars. For the sake of simplicity, we will assume that...
10 min read
In the world of Java programming, data processing is a common task that often involves manipulating collections of objects. Prior to the release of Java 8, performing operations on collections required writing verbose and error-prone code using loops or external libraries. However, with the introduction of...
5 min read
Duck number is another special positive non-zero number that contains zero in it. The digit zero should not be presented at the starting of the number. Zero can be present at any of the positions except the beginning of the number. Let's understand some examples of Duck...
3 min read
Difference Between Character Stream and Byte Stream in Java In Java, the streams are used for input and output operations by allowing data to be read from or written to a source or destination. Java offers two types of streams: Character stream Byte stream These streams can be different in...
6 min read
What is a Java Agent? Java agents are instruments that can help to modify bytecode since they run concurrently with a Java program. These agents can be attached with the JVM by using the -javaagent option that enable them to intercept ClassLoaders and perform transformation to the...
4 min read
SHA is an abbreviation for Secure Hash Algorithm. In and is one of the most alent cryptographic hash functions. A cryptographic hash can be used to create a text signature or data file. Now, SHA is nothing but a cryptographic hash function that takes input...
4 min read
? There are different versions of Java is available. Some of the applications generally require different version because of compatibility problems. In this section, we will learn how to check the Java version in Windows using CMD. A version string contains a version number optionally followed by pre-release...
2 min read
UUID is a widely used 128-bit long unique identification number in the computer system. It consists of hex-digits separated by four hyphens. In this section, we will discuss what is UUID and how to randomly generate UUID (version 4) in Java. UUID UUID stands for Universally Unique IDentifier....
3 min read
This article aims to explain how to create an instance of an abstract class in Java. We will look at the different ways to create an instance of an abstract class and the pros and cons of each approach. We will also discuss the importance of...
6 min read
We request you to subscribe our newsletter for upcoming updates.
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India