Java – Merging two String[] Array and Sorting

In this article, we will discuss how to merge two arrays and then sort according to natural order i.e.; ascending order. Well, by passing Comparator object we can sort in reverse order as well.

Sorting String[] Arrays after merging 2 Arrays:

Steps:

  1. Create Array 1 with String values {“Sachin”, “Dravid”, “Ganguly”, “Laxman”, “Sehwag”}
  2. Create Array 2 with String values {“Kumble”, “Srinath”, “Prasad”, “Zaheer”}
  3. Create third array of size, by adding size of 1st array and 2nd array
  4. Assign values from String[] array 1 to new third array while iterating 1st array (0-s1)
  5. Similarly, assign values from String[] array 2 to new third array while iterating 2nd array(s1 – s2)
  6. Then finally invoke Arrays.sort(mergedArray); on the merged array for sorting merged elements in ascending order

MergeAndSortStringArray.java

package in.bench.resources.java.arrays.sorting;

import java.util.Arrays;

public class MergeAndSortStringArray {

	public static void main(String[] args) {

		// sample String[] array
		String[] strArray1 = {
				"Sachin",
				"Dravid",
				"Ganguly",
				"Laxman",
				"Sehwag"
		};
		String[] strArray2 = {
				"Kumble",
				"Srinath",
				"Prasad",
				"Zaheer"
		};

		// create another String[] array of size = arr1 + arr2
		String[] thirdArray =
				new String[strArray1.length + strArray2.length];

		// iterate through 1st strArray1 and
		// assign values to thridArray
		for(int index = 0; index < strArray1.length; index++) {
			thirdArray[index] = strArray1[index];
		}

		// iterate through 2nd strArray2 and
		// assign values to thridArray
		for(int index = strArray1.length, i=0;
				index < strArray1.length + strArray2.length;
				index++, i++) {

			thirdArray[index] = strArray2[i];
		}

		// sorting MERGED String[] array in ascending-order
		Arrays.sort(thirdArray);

		// after sorting
		System.out.println("Sorting merged array : \n");
		for(String str : thirdArray) {
			System.out.println(str);
		}
	}
}

Output:

Sorting merged array : 

Dravid
Ganguly
Kumble
Laxman
Prasad
Sachin
Sehwag
Srinath
Zaheer

Hope, you found this article very helpful. If you have any suggestion or want to contribute any other way or tricky situation you faced during Interview hours, then share with us. We will include that code here.

References:

Happy Coding !!
Happy Learning !!

Java - How ConcurrentModificationException can be handled ?
Java - Sorting Arrays in Ascending and Descending order