When developing with Java, you often need to combine data from different sources—like a database and local logic—into a single array.
However, since Java arrays are fixed-length, you cannot simply use an operator like array1 + array2 as you might in other scripting languages. To join them, you must allocate a new array and copy the elements.
In this guide, we’ll explore the best techniques to concatenate arrays in Java, ranging from the high-performance System.arraycopy to the modern Stream API, and even handling binary data with byte[].
1. The Fastest Method: System.arraycopy()
System.arraycopy is the most fundamental and high-performance way to join arrays. While the syntax is a bit verbose, it works for both primitive types (int, byte, etc.) and reference types (String, Object).
Example: Concatenating two int arrays
import java.util.Arrays;
public class ArrayCopyExample {
public static void main(String[] args) {
int[] array1 = { 1, 2, 3 };
int[] array2 = { 4, 5, 6 };
// 1. Calculate and allocate the size for the new array
int[] result = new int[array1.length + array2.length];
// 2. Copy array1 to the beginning (index 0) of result
System.arraycopy(array1, 0, result, 0, array1.length);
// 3. Copy array2 to the end (index array1.length) of result
System.arraycopy(array2, 0, result, array1.length, array2.length);
System.out.println("Result: " + Arrays.toString(result));
}
}
Output:
Result: [1, 2, 3, 4, 5, 6]
The method signature is System.arraycopy(src, srcPos, dest, destPos, length). This is the gold standard for handling large datasets or binary operations where performance is critical.
2. The Modern Way: Stream API (Java 8+)
If you are using Java 8 or later, the Stream API provides a more declarative and readable way to join arrays, especially for reference types like String[].
Example: Concatenating String arrays
import java.util.Arrays;
import java.util.stream.Stream;
public class StreamConcatExample {
public static void main(String[] args) {
String[] array1 = { "Java", "Python" };
String[] array2 = { "C#", "Ruby" };
// Use Stream.concat to join and convert back to an array
String[] result = Stream.concat(Arrays.stream(array1), Arrays.stream(array2))
.toArray(String[]::new);
System.out.println("Result: " + Arrays.toString(result));
}
}
Note for Primitives: When dealing with primitive arrays like int[], you should use IntStream instead of the generic Stream.
int[] result = IntStream.concat(Arrays.stream(array1), Arrays.stream(array2)).toArray();
3. Joining Array Elements into a Single String
Sometimes "concatenating arrays" means you want to join all elements into a single delimited string (e.g., a CSV). In this case, String.join() is the best practice.
Example: Creating a comma-separated string
public class StringJoinExample {
public static void main(String[] args) {
String[] fruits = { "Apple", "Banana", "Orange" };
// Join with a comma
String csv = String.join(",", fruits);
// Join without a delimiter
String combined = String.join("", fruits);
System.out.println("CSV Format: " + csv);
System.out.println("Combined: " + combined);
}
}
This approach is much cleaner than manually looping with a StringBuilder.
4. Using List (ArrayList) for Flexibility
If you need to add or remove elements frequently, it is often better to handle data as a List rather than a fixed-length array.
Example: Using Collections.addAll()
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class ListJoinExample {
public static void main(String[] args) {
String[] array1 = { "A", "B" };
String[] array2 = { "C", "D" };
List<String> list = new ArrayList<>();
// Add all elements from both arrays to the list
Collections.addAll(list, array1);
Collections.addAll(list, array2);
System.out.println("List Content: " + list);
}
}
If you absolutely need an array at the end, you can convert it back using list.toArray(new String[0]).
Extra: Concatenating byte[] for Binary Data
For image processing or network communication, you might want to join byte arrays. While System.arraycopy is common, ByteArrayOutputStream is more intuitive for streaming data.
import java.io.ByteArrayOutputStream;
import java.io.IOException;
public class ByteJoinExample {
public static void main(String[] args) throws IOException {
byte[] b1 = { 0x01, 0x02 };
byte[] b2 = { 0x03, 0x04 };
try (ByteArrayOutputStream output = new ByteArrayOutputStream()) {
output.write(b1);
output.write(b2);
byte[] result = output.toByteArray();
}
}
}
Conclusion
The right tool for joining arrays depends on your requirements:
-
Performance: Use
System.arraycopy(). -
Readability (Modern Java): Use
Stream.concat(). -
Formatting: Use
String.join(). -
Dynamic Sizing: Use
ArrayList.
Originally published at: [https://code-izumi.com/java/combine-arrays/]
Top comments (0)