Skip to content

Java join two arrays example

Java join two arrays example shows how to join two arrays in Java. The example also shows various ways to join two arrays using the arraycopy, Apache Commons, Collections, and Java 8 Streams.

How to join two arrays in Java?

There are various ways using which you can join two arrays in Java.

1) Join two arrays using the arraycopy method of the System class

You can use the arraycopy method of System class to copy elements to a third array one by one.

This method copies elements of the source array starting from srcStartPosition to specified destStartPosition of the destination array. The length parameter denotes the number of elements to be copied from source to destination.

This method may throw ArrayIndexOutOfBoundsException, NullPointerException or ArrayStoreException.

Please see the below-given example that shows how to copy an array using this method.

Output

2) Join two arrays using Apache commons library

If you are using the Apache Commons library, you can use the addAll method of ArrayUtils class.

This method adds all elements of the specified arrays to a new array.

Example

Output

3) Join two arrays using the Collections class

Though not efficient, you can use the Collections class to join two arrays using the addAll method.

Output

4) Join two arrays using Java 8 streams

If you are using Java version 8 or above, you can use streams to join two arrays in a single line as given below.

Output

You can also use flatMap and toArray of Stream to join arrays as given below.

Output

What is the best way to join two arrays in Java?

Using the Stream and Collections approach (3 and 4) will be the slowest way in terms of performance. Using Apache Commons (approach 2) is the simplest way to join two arrays while using the  arraycopy method of Systems class (approach 1) is the fastest and most efficient way to join two arrays in Java.

This example is a part of the Java Array tutorial with examples.

Please let me know your views in the comments section below.

About the author

Leave a Reply

Your email address will not be published.