I need to concatenate two String
arrays in Java.
void f(String[] first, String[] second) {
String[] both = ???
}
What is the easiest way to do this?
I need to concatenate two String
arrays in Java.
void f(String[] first, String[] second) {
String[] both = ???
}
What is the easiest way to do this?
It's possible to write a fully generic version that can even be extended to concatenate any number of arrays. This versions require Java 6, as they use
Arrays.copyOf()
Both versions avoid creating any intermediary
List
objects and useSystem.arraycopy()
to ensure that copying large arrays is as fast as possible.For two arrays it looks like this:
And for a arbitrary number of arrays (>= 1) it looks like this:
How about simply
And just do
Array.concat(arr1, arr2)
. As long asarr1
andarr2
are of the same type, this will give you another array of the same type containing both arrays.One-liner in Java 8:
Or:
The Functional Java library has an array wrapper class that equips arrays with handy methods like concatenation.
...and then
To get the unwrapped array back out, call
This works, but you need to insert your own error checking.
It's probably not the most efficient, but it doesn't rely on anything other than Java's own API.