Explain Codes LogoExplain Codes Logo

How can I concatenate two arrays in Java?

java
array-utility-functions
java-streams
array-concatenation
Alex KataevbyAlex Kataev·Sep 18, 2024
TLDR

Ping-pong arrays together in Java with the staple System.arraycopy():

int[] array1 = {1, 2, 3}, array2 = {4, 5, 6}, combined = new int[array1.length + array2.length]; // Here comes the first serve System.arraycopy(array1, 0, combined, 0, array1.length); // And the return System.arraycopy(array2, 0, combined, array1.length, array2.length);

array1 and array2 engage in a rally, resulting in a championship-winning point in combined.

Effective Alternatives

Apache Commons Lang: The One-Liner Hero

For a swift fix, Apache Commons Lang's ArrayUtils.addAll steals the grandstand:

// Not all heroes wear capes String[] merged = ArrayUtils.addAll(array1, array2);

A concise yet robust solution that provides a trove of other array utility functions.

Java Streams: Functional Flair

For those who prefer a functional upbringing in their code, Java Streams offer a contemporary solution:

// Making a splash with Streams Integer[] merged = Stream.concat(Arrays.stream(array1), Arrays.stream(array2)) .toArray(Integer[]::new);

Or, if you have 3 or more 'ducklings' to line up in a row, flatMap is the mother duck you're seeking:

// All aboard the flatMap ship! Integer[] merged = Stream.of(array1, array2, array3) .flatMap(Arrays::stream) .toArray(Integer[]::new);

Generics: One Size Does Not Fit All

If it's generic arrays you're wrestling with, Array.newInstance will ensure a champion grapple:

// Instantiating a new array of the right size and type T[] merged = (T[]) Array.newInstance(array1.getClass().getComponentType(), array1.length + array2.length);

Guava: A Sweet Solution

For Guava enthusiasts, ObjectArrays.concat and Ints.concat provide swift and easy-to-read solutions:

// The sweet taste of Guava String[] merged = ObjectArrays.concat(array1, array2); int[] combined = Ints.concat(array1, array2);

Crafting Robust Code

Take null arrays and performance impact into account to stride towards NullPointerException-free and well-performing code.

Key Considerations

Ensure type compatibility to dodge IllegalArgumentException's and check a.getClass().isArray() to confirm array work. Use (T[]) for safe unchecked casting and lean on reflection to decipher the common component type.

Multiple Arrays Unite!

For a glorious union of multiple arrays, overloaded methods or a concatAll() function can be your crown jewel.