In this post, we will write a 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.- Java program to Count Number of Duplicate Words in String
- Java Program to Count Number of Words in Given String
- Java Program to Count the Number of Occurrences of Substring in a String
- Java Program to Count the Occurrences of Each Character in String
- Java Program to Merge two String Arrays
- Java Program to Remove Duplicate Words from String
- Java Program to Reverse a String(5 ways)
- Java Program to Reverse Each Word of a String
- Java Program to Swap Two Strings
- How to Check if the String Contains only Digits
- How to Check if the String Contains only Letters
- How to Check If the String Contains Only Letters or Digits
Free Spring Boot Tutorial | Full In-depth Course | Learn Spring Boot in 10 Hours
Watch this course on YouTube at Spring Boot Tutorial | Fee 10 Hours Full Course