merge 2 arrays of string values. - Java java.lang

Java examples for java.lang:String Array

Description

merge 2 arrays of string values.

Demo Code


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

public class Main {

  /**/*from ww  w  .j  a  v  a 2  s  . co m*/
   * This String utility or util method can be used to merge 2 arrays of string
   * values. If the input arrays are like this array1 = {"a", "b" , "c"} array2 =
   * {"c", "d", "e"} Then the output array will have {"a", "b" , "c", "d", "e"}
   * 
   * This takes care of eliminating duplicates and checks null values.
   * 
   * @param values
   * @return
   */
  public static String[] mergeStringArrays(String array1[], String array2[]) {
    if (array1 == null || array1.length == 0)
      return array2;
    if (array2 == null || array2.length == 0)
      return array1;
    List array1List = Arrays.asList(array1);
    List array2List = Arrays.asList(array2);
    List result = new ArrayList(array1List);
    List tmp = new ArrayList(array1List);
    tmp.retainAll(array2List);
    result.removeAll(tmp);
    result.addAll(array2List);
    return ((String[]) result.toArray(new String[result.size()]));
  }
}

Related Tutorials