Java How To Join Two Arrays
It isn’t as easy as it should be to join two arrays in Java. It isn’t hard though and can be done with a relatively small amount of effort.
We are going to show you a few different ways you can join multiple arrays in Java. We are going to start out assuming that we have the following two arrays already defined for each example and that we want the result to be saved in a new array “a3”.
int[] a1 = {1, 2, 3};
int[] a2 = {4, 5, 6};
Method 1 - Using System.arraycopy
You can use the System.arraycopy method to copy both arrays into a third, new array.
int a1Len = a1.length;
int a2Len = a2.length;
int[] a3 = new int[a1Len + a1Len];
System.arraycopy(a1, 0, a3, 0, aLen);
System.arraycopy(a2, 0, a3, a1Len, a2Len);
Method 2 - Using ArrayUtils
This is probably the easiest way of joining two arrays together in Java but it requires Apache Commons to be installed. This is a third party library but Apache Commons is very convenient and widely used.
int[] both = ArrayUtils.addAll(a1, a2);
Method 3 - Using Stream
In Java 8 and up you can use Stream. This method looks a bit messy but does accomplish our goal using only a single line of text and without using any third party libraries.
int[] a3 = Stream.concat(Arrays.stream(a1), Arrays.stream(a2)).toArray(int[]::new);
Method 4 - Looping to Join Two Arrays
You can also do it manually by just looping over each of the two arrays and copying the elements into the new array one by one.
int length = a1.length + a2.length;
int[] a3 = new int[length];
int c = 0;
for (int e : a1) {
result[c] = element;
c++;
}
for (int e : a2) {
result[c] = element;
c++;
}