How to Concatenate Two Arrays in Java
In Java, concatenating two arrays isn’t as straightforward as using the +
operator, but there are several efficient ways to achieve this. Here are some of the most popular and reliable methods for merging arrays, from using libraries like Apache Commons and Guava to native Java solutions that avoid extra dependencies.
1. Using Apache Commons ArrayUtils
Apache Commons Lang provides a one-line solution to concatenate arrays with the ArrayUtils.addAll()
method. If you’re already using Apache Commons in your project, this is an efficient and straightforward option.
import org.apache.commons.lang3.ArrayUtils;
String[] both = ArrayUtils.addAll(first, second);
This method requires the Apache Commons Lang library, so consider this option if you’re comfortable with adding a library dependency.
Read more »