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?
Here's a method that will concatenate 2 arrays of type T
T[] concat(T[] A, T[] B) {
T[] C= new T[A.length+B.length];
System.arraycopy(A, 0, C, 0, A.length);
System.arraycopy(B, 0, C, A.length, B.length);
return C;
}
(source: Sun Forum )
I found a one-line solution from the good old Apache Commons Lang library. ArrayUtils.addAll(Object[], Object[]). Code:
String[] both = ArrayUtils.addAll(first, second);
The Functional Java library has an array wrapper class that equips arrays with handy methods like concatenation.
import static fj.data.Array.array;
...and then
Array<String> both = array(first).append(array(second));
To get the unwrapped array back out, call
String[] s = both.array();
Using only Javas own API:
String[] join(String[]... arrays) {
// calculate size of target array
int size = 0;
for (String[] array : arrays) {
size += array.length;
}
// create list of appropriate size
java.util.List list = new java.util.ArrayList(size);
// add arrays
for (String[] array : arrays) {
list.addAll(java.util.Arrays.asList(array));
}
// create and return final array
return list.toArray(new String[size]);
}
Now, this code ist not the most efficient, but it relies only on standard java classes and is easy to understand. It works for any number of String[] (even zero arrays).
Here's an adaptation of silvertab's solution, with generics retrofitted:
static <T> T[] concat(T[] a, T[] b) {
final int alen = a.length;
final int blen = b.length;
final T[] result = (T[]) java.lang.reflect.Array.
newInstance(a.getClass().getComponentType(), alen + blen);
System.arraycopy(a, 0, result, 0, alen);
System.arraycopy(b, 0, result, alen, blen);
return result;
}
NOTE: See Joachim's answer for a Java 6 solution. Not only does it eliminate the warning; it's also shorter, more efficient and easier to read!
I've recently fought problems with excessive memory rotation. If a and/or b are known to be commonly empty, here is another adaption of silvertab's code (generified too):
private static <T> T[] concat(T[] a, T[] b) {
final int alen = a.length;
final int blen = b.length;
if (alen == 0) {
return b;
}
if (blen == 0) {
return a;
}
final T[] result = (T[]) java.lang.reflect.Array.
newInstance(a.getClass().getComponentType(), alen + blen);
System.arraycopy(a, 0, result, 0, alen);
System.arraycopy(b, 0, result, alen, blen);
return result;
}
(In either case, array re-usage behaviour shall be clearly JavaDoced!)
String[] both = Arrays.asList(first).addAll(Arrays.asList(second)).toArray();
Using the Java API:
String[] f(String[] first, String[] second) {
List<String> both = new ArrayList<String>(first.length + second.length);
Collections.addAll(both, first);
Collections.addAll(both, second);
return both.toArray(new String[] {});
}
If you'd like to work with ArrayLists in the solution, you can try this:
public final String [] f(final String [] first, final String [] second) {
// Assuming non-null for brevity.
final ArrayList<String> resultList = new ArrayList<String>(Arrays.asList(first));
resultList.addAll(new ArrayList<String>(Arrays.asList(second)));
return resultList.toArray(new String [resultList.size()]);
}
I tested below code and worked ok
Also I'm using library: org.apache.commons.lang.ArrayUtils
public void testConcatArrayString(){
String[] a = null;
String[] b = null;
String[] c = null;
a = new String[] {"1","2","3","4","5"};
b = new String[] {"A","B","C","D","E"};
c = (String[]) ArrayUtils.addAll(a, b);
if(c!=null){
for(int i=0; i<c.length; i++){
System.out.println("c[" + (i+1) + "] = " + c[i]);
}
}
}
Regards
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 use System.arraycopy()
to ensure that copying large arrays is as fast as possible.
For two arrays it looks like this:
public static <T> T[] concat(T[] first, T[] second) {
T[] result = Arrays.copyOf(first, first.length + second.length);
System.arraycopy(second, 0, result, first.length, second.length);
return result;
}
And for a arbitrary number of arrays (>= 1) it looks like this:
public static <T> T[] concatAll(T[] first, T[]... rest) {
int totalLength = first.length;
for (T[] array : rest) {
totalLength += array.length;
}
T[] result = Arrays.copyOf(first, totalLength);
int offset = first.length;
for (T[] array : rest) {
System.arraycopy(array, 0, result, offset, array.length);
offset += array.length;
}
return result;
}
An easy, but inefficient, way to do this (generics not included):
ArrayList baseArray = new ArrayList(Arrays.asList(array1));
baseArray.addAll(Arrays.asList(array2));
String concatenated[] = (String []) baseArray.toArray(new String[baseArray.size()]);
A simple variation allowing the joining of more than one array:
public static String[] join(String[]...arrays) {
final List<String> output = new ArrayList<String>();
for(String[] array : arrays) {
output.addAll(Arrays.asList(array));
}
return output.toArray(new String[output.size()]);
}
A type independent variation (UPDATED - thanks to Volley for instantiating 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()));
}
Some of the solutions above dont work for primitive types specifically byte. Can you tell me an implementation which works for the byte[]
I don't know why the top-rated answer is rated so high (and why can't I comment on it).
String[] both = ArrayUtils.addAll(first, second);
doesn't even compile as there is no overloaded addAll which returns a String array.
/**
* Concatenates two arrays.
*
* @param array1 - first array
* @param array2 - second array
* @param <T> - object class
* @return array contatenation
*/
public static <T> T[] concatenate(T[] array1, T... array2) {
List<T> result = new ArrayList<T>();
result.addAll(Arrays.asList(array1));
result.addAll(Arrays.asList(array2));
return result.toArray(array1);
}