What is the easiest way to combine two arrays in Java?
I have two String arrays in Java, and I need to merge them into a single array.
For example:
void f(String[] first, String[] second) {
String[] both = ???;
}
How can I achieve this efficiently? Is there a built-in method in Java that simplifies this process, or do I need to use a loop? I’m looking for the best way to combine two arrays in Java while keeping the code clean and efficient.
Ah, I’ve worked with array operations quite a bit. If you’re using Java 8 or later, the Stream.concat()
method makes combining two arrays super clean and concise:
import java.util.stream.Stream;
void f(String[] first, String[] second) {
String[] both = Stream.concat(Stream.of(first), Stream.of(second))
.toArray(String[]::new);
}
Why this? It’s neat, readable, and avoids manual looping. Plus, it works with any array type—making it a solid option for most use cases. This is a great way to Java combine two arrays efficiently.
Building on @jacqueline-bosco’s point—if performance is your main concern, System.arraycopy()
is the way to go. It’s faster and more efficient for larger arrays because it directly manipulates memory:
void f(String[] first, String[] second) {
String[] both = new String[first.length + second.length];
System.arraycopy(first, 0, both, 0, first.length);
System.arraycopy(second, 0, both, first.length, second.length);
}
Why this?
When handling large datasets, this method is optimized for speed. It’s my go-to when I need to Java combine two arrays without sacrificing performance.
Using ArrayList (If You Need Flexibility)
If you might modify the array later, an ArrayList can be a better option:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
void f(String first, String second) {
List list = new ArrayList<>(Arrays.asList(first));
list.addAll(Arrays.asList(second));
String both = list.toArray(new String[0]);
}
Why this? It allows you to easily add or remove elements before converting it back to an array.