Java Program to Merge two String Arrays

In this post, we will write Java program to merge 2 arrays of string values.
In below program, the mergeStringArrays() method takes care of eliminating duplicates and checks null values.

Java Program to Merge two String Arrays

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Java Program to merge 2 arrays of string values.
 * @author javaguides.net
 *
 */
public class MergeTwoStringarrays {
 
 private static String[] mergeStringArrays(String array1[], String array2[]) {

  if (array1 == null || array1.length == 0)
   return array2;
  if (array2 == null || array2.length == 0)
   return array1;
  List<String> firstList = Arrays.asList(array1);
  List<String> secondList = Arrays.asList(array2);
  
  List<String> result = new ArrayList<String>(firstList);
  List<String> tmp = new ArrayList<String>(firstList);
  
  tmp.retainAll(secondList);
  result.removeAll(tmp);
  result.addAll(secondList);
  return ((String[]) result.toArray(new String[result.size()]));
 }
 
 public static void main(String[] args) {
  String[] strArray = mergeStringArrays(new String[] {"abc","xyz","pqr"}, 
                                                      new String[] {"abc","ABC","PQR"});
  for(String string : strArray){
   System.out.println(string);
  }
 }
}
Output:
xyz
pqr
abc
ABC
PQR
Note that in above program, we have used retainAll(Collection<?> c) API of ArrayList implementation class.

retainAll(Collection<?> c) Method

retainAll(Collection<?> c) - This method retains only the elements in this list that are contained in the specified collection (optional operation). In other words, removes from this list all of its elements that are not contained in the specified collection.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Related String Programs

Note that these programs are asked in interviews.

Comments