Java Basic Examples

Java join two arrays example

Java join two arrays example shows how to join two arrays in Java. Example also shows various ways to join two arrays using 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 arraycopy method of System class

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

This method copies elements of source array starting from srcStartPosition to specified destStartPosition of destination array. Length denotes number of elements to be copied from source to destination.

This method may throw ArrayIndexOutOfBoundsException, NullPointerException or ArrayStoreException.

Example

Output

2)    Join two arrays using Apache commons library

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

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

Example

Output

3)    Join two arrays using Collections class

Though not efficient, you can use Collections class to join two arrays using 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 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.

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

Join 1000+ fellow learners! Enter your email address below: