How can I concatenate two arrays in Java?

后端 未结 30 1973
走了就别回头了
走了就别回头了 2020-11-21 06:05

I need to concatenate two String arrays in Java.

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

What is t

30条回答
  •  滥情空心
    2020-11-21 06:24

    Using Stream in Java 8:

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

    Or like this, using flatMap:

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

    To do this for a generic type you have to use reflection:

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

提交回复
热议问题