我需要在Java中连接两个字符串数组。

void f(String[] first, String[] second) {
    String[] both = ???
}

哪种方法最简单?


当前回答

在Java 8中使用流:

String[] both = Stream.concat(Arrays.stream(a), Arrays.stream(b))
                      .toArray(String[]::new);

或者像这样,使用flatMap:

String[] both = Stream.of(a, b).flatMap(Stream::of)
                      .toArray(String[]::new);

要对泛型类型执行此操作,必须使用反射:

@SuppressWarnings("unchecked")
T[] both = Stream.concat(Arrays.stream(a), Arrays.stream(b)).toArray(
    size -> (T[]) Array.newInstance(a.getClass().getComponentType(), size));

其他回答

ArrayList<String> both = new ArrayList(Arrays.asList(first));
both.addAll(Arrays.asList(second));

both.toArray(new String[0]);

哇!这里有很多复杂的答案,包括一些依赖于外部依赖的简单答案。这样做怎么样:

String [] arg1 = new String{"a","b","c"};
String [] arg2 = new String{"x","y","z"};

ArrayList<String> temp = new ArrayList<String>();
temp.addAll(Arrays.asList(arg1));
temp.addAll(Arrays.asList(arg2));
String [] concatedArgs = temp.toArray(new String[arg1.length+arg2.length]);
 /**
     * With Java Streams
     * @param first First Array
     * @param second Second Array
     * @return Merged Array
     */
    String[] mergeArrayOfStrings(String[] first, String[] second) {
        return Stream.concat(Arrays.stream(first), Arrays.stream(second)).toArray(String[]::new);
    }

我有一个简单的方法。您不想浪费时间研究复杂的java函数或库。但返回类型应该是String。

String[] f(String[] first, String[] second) {

    // Variable declaration part
    int len1 = first.length;
    int len2 = second.length;
    int lenNew = len1 + len2;
    String[] both = new String[len1+len2];

    // For loop to fill the array "both"
    for (int i=0 ; i<lenNew ; i++){
        if (i<len1) {
            both[i] = first[i];
        } else {
            both[i] = second[i-len1];
        }
    }

    return both;

}

这么简单。。。

一个与类型无关的变体(已更新-感谢Volley实例化T):

@SuppressWarnings("unchecked")
public static <T> T[] join(T[]...arrays) {

    final List<T> output = new ArrayList<T>();

    for(T[] array : arrays) {
        output.addAll(Arrays.asList(array));
    }

    return output.toArray((T[])Array.newInstance(
        arrays[0].getClass().getComponentType(), output.size()));
}