Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

How can I concatenate two arrays in Java?

I need to connect two String arrays in Java.

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


What is the most effortless approach to do this?
by

2 Answers

espadacoder11
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));
kshitijrana14
I found a one-line solution from the good old Apache Commons Lang library.
ArrayUtils.addAll(T[], T...)
Code:
String[] both = ArrayUtils.addAll(first, second);

Login / Signup to Answer the Question.