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

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

哪种方法最简单?


当前回答

我使用下一个方法使用java8连接任意数量的相同类型的数组:

public static <G> G[] concatenate(IntFunction<G[]> generator, G[] ... arrays) {
    int len = arrays.length;
    if (len == 0) {
        return generator.apply(0);
    } else if (len == 1) {
        return arrays[0];
    }
    int pos = 0;
    Stream<G> result = Stream.concat(Arrays.stream(arrays[pos]), Arrays.stream(arrays[++pos]));
    while (pos < len - 1) {
        result = Stream.concat(result, Arrays.stream(arrays[++pos]));
    }
    return result.toArray(generator);
}

用法:

 concatenate(String[]::new, new String[]{"one"}, new String[]{"two"}, new String[]{"three"}) 

or

 concatenate(Integer[]::new, new Integer[]{1}, new Integer[]{2}, new Integer[]{3})

其他回答

另一种思考问题的方式。要连接两个或多个数组,必须列出每个数组的所有元素,然后构建一个新数组。这听起来像是创建一个List<T>,然后调用它上的Array。其他一些答案使用ArrayList,这很好。但如何实现我们自己的呢?这并不难:

private static <T> T[] addAll(final T[] f, final T...o){
    return new AbstractList<T>(){

        @Override
        public T get(int i) {
            return i>=f.length ? o[i - f.length] : f[i];
        }

        @Override
        public int size() {
            return f.length + o.length;
        }

    }.toArray(f);
}

我相信上面的解决方案相当于使用System.arraycopy的解决方案。然而,我认为这个解决方案有其自身的优点。

public static String[] toArray(String[]... object){
    List<String> list=new ArrayList<>();
    for (String[] i : object) {
        list.addAll(Arrays.asList(i));
    }
    return list.toArray(new String[list.size()]);
}

在Java 8中

public String[] concat(String[] arr1, String[] arr2){
    Stream<String> stream1 = Stream.of(arr1);
    Stream<String> stream2 = Stream.of(arr2);
    Stream<String> stream = Stream.concat(stream1, stream2);
    return Arrays.toString(stream.toArray(String[]::new));
}

在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));

这是可行的,但您需要插入自己的错误检查。

public class StringConcatenate {

    public static void main(String[] args){

        // Create two arrays to concatenate and one array to hold both
        String[] arr1 = new String[]{"s","t","r","i","n","g"};
        String[] arr2 = new String[]{"s","t","r","i","n","g"};
        String[] arrBoth = new String[arr1.length+arr2.length];

        // Copy elements from first array into first part of new array
        for(int i = 0; i < arr1.length; i++){
            arrBoth[i] = arr1[i];
        }

        // Copy elements from second array into last part of new array
        for(int j = arr1.length;j < arrBoth.length;j++){
            arrBoth[j] = arr2[j-arr1.length];
        }

        // Print result
        for(int k = 0; k < arrBoth.length; k++){
            System.out.print(arrBoth[k]);
        }

        // Additional line to make your terminal look better at completion!
        System.out.println();
    }
}

它可能不是最有效的,但除了Java自己的API之外,它不依赖其他任何东西。