Java Array Merge mergeStringArrays(String array1[], String array2[])

Here you can find the source of mergeStringArrays(String array1[], String array2[])

Description

This String utility or util method can be used to merge 2 arrays of string values.

License

Apache License

Parameter

Parameter Description
values a parameter

Declaration

public static String[] mergeStringArrays(String array1[], String array2[]) 

Method Source Code

//package com.java2s;
/*/* w ww. j a v  a2s .  c  o m*/
 * Licensed to Eolya and Dominique Bejean under one
 * or more contributor license agreements. 
 * Eolya licenses this file to you under the 
 * Apache License, Version 2.0 (the "License"); 
 * you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

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

import java.util.List;

public class Main {
    /**
     * 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<String> array1List = Arrays.asList(array1);
        List<String> array2List = Arrays.asList(array2);
        List<String> result = new ArrayList<String>(array1List);
        List<String> tmp = new ArrayList<String>(array1List);
        tmp.retainAll(array2List);
        result.removeAll(tmp);
        result.addAll(array2List);
        return ((String[]) result.toArray(new String[result.size()]));
    }
}

Related

  1. mergeStringArray(String[] array, String seperator)
  2. mergeStringArray(String[] ary1, String[] ary2)
  3. mergeStringArray(String[] inp1, String[] inp2)
  4. mergeStringArray(String[] input)
  5. mergeStringArrayFromIndex(String[] arrayString, int i)
  6. mergeStringArrays(String array1[], String array2[], String array3[])
  7. mergeStringArrays(String[] array1, String[] array2)
  8. mergeStringArrays(String[][] arrayOfArrays)
  9. mergeStrings(String[] x, String[] y)