Here you can find the source of mergeStringArrays(String[] array1, String[] array2)
Parameter | Description |
---|---|
array1 | the first array (can be <code>null</code>) |
array2 | the second array (can be <code>null</code>) |
null
if both given arrays were null
)
public static String[] mergeStringArrays(String[] array1, String[] array2)
//package com.java2s; /*/*from w ww .ja v a 2s . co m*/ * Copyright 2002-2011 the original author or authors. * * Licensed 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.*; public class Main { /** * Merge the given String arrays into one, with overlapping * array elements only included once. * <p>The order of elements in the original arrays is preserved * (with the exception of overlapping elements, which are only * included on their first occurrence). * @param array1 the first array (can be <code>null</code>) * @param array2 the second array (can be <code>null</code>) * @return the new array (<code>null</code> if both given arrays were <code>null</code>) */ public static String[] mergeStringArrays(String[] array1, String[] array2) { if (isObjectEmpty(array1)) { return array2; } if (isObjectEmpty(array2)) { return array1; } List<String> result = new ArrayList<String>(); result.addAll(Arrays.asList(array1)); for (String str : array2) { if (!result.contains(str)) { result.add(str); } } return toStringArray(result); } /** * Determine whether the given array is empty: * i.e. <code>null</code> or of zero length. * @param array the array to check */ public static boolean isObjectEmpty(Object[] array) { return (array == null || array.length == 0); } /** * Copy the given Collection into a String array. * The Collection must contain String elements only. * @param collection the Collection to copy * @return the String array (<code>null</code> if the passed-in * Collection was <code>null</code>) */ public static String[] toStringArray(Collection<String> collection) { if (collection == null) { return null; } return collection.toArray(new String[collection.size()]); } /** * Copy the given Enumeration into a String array. * The Enumeration must contain String elements only. * @param enumeration the Enumeration to copy * @return the String array (<code>null</code> if the passed-in * Enumeration was <code>null</code>) */ public static String[] toStringArray(Enumeration<String> enumeration) { if (enumeration == null) { return null; } List<String> list = Collections.list(enumeration); return list.toArray(new String[list.size()]); } }