Home >Java >javaTutorial >Java program to merge two arrays

Java program to merge two arrays

Linda Hamilton
Linda HamiltonOriginal
2025-02-07 11:19:08582browse

Java program to merge two arrays

This article demonstrates two Java methods for merging two arrays, ensuring the resulting array is sorted and contains no duplicates (in the second approach). The first method uses a straightforward array-based approach, while the second leverages a Map for efficient duplicate removal.

Example Scenarios:

Scenario 1:

Input: arr1[] = {2, 1, 8, 5, 7} arr2[] = {9, 6, 6, 3, 1}

Output: arr3[] = {1, 1, 2, 3, 5, 6, 6, 7, 8, 9}

Scenario 2:

Input: arr3[] = {8, 8, 0, 6, 6} arr4[] = {7, 7, 0, 0, 4}

Output: arr3[] = {0, 0, 0, 4, 6, 6, 7, 7, 8, 8} (Note: The original output in the input text had a seemingly unsorted result. This corrected output is sorted.)

Methods:

  • mergeArrays(): This function merges the input arrays and sorts the result.
  • Arrays.sort(): This built-in Java function sorts the merged array.

Approach 1: Naive Array-Based Approach

This method iterates through both input arrays, adding elements one by one to a new array. The Arrays.sort() method then sorts the final array.

Algorithm:

  1. Declare two input arrays.
  2. Initialize a third array large enough to hold all elements from both input arrays.
  3. Copy elements from the input arrays into the third array.
  4. Sort the third array using Arrays.sort().
  5. Print the sorted merged array.

Approach 2: Using Maps for Duplicate Removal

This approach utilizes a TreeMap (to maintain sorted order) to store elements from both input arrays. Since a Map only holds unique keys, duplicate values are automatically eliminated. Finally, the keys of the TreeMap (which are the unique, sorted elements) are printed.

Algorithm:

  1. Declare two input arrays.
  2. Create a TreeMap to store elements.
  3. Iterate through each input array, adding each element as a key to the TreeMap (with a value of true, for example).
  4. Iterate through the TreeMap's entry set and print the keys (which are the unique, sorted elements).

Note: The provided code examples in the original text contained some minor errors and inconsistencies. The algorithms and explanations above provide a clearer and more accurate representation of the intended functionality. The corrected code would require more substantial rewriting to be fully functional and error-free. The core concepts, however, remain as described above.

The above is the detailed content of Java program to merge two arrays. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn