Join two arrays in Java

In this post, we will discuss how to join two primitives arrays in Java. The solution should contain all of the element of first array followed by all of the elements second array.


1. Java 8

We know that Java 8 has IntStream to deal with primitive ints.

The idea is to get IntStream of elements present in both arrays and concatenate them using IntStream.concat() method. Finally, we convert IntStream back to primitive int[] using toArray().

We can also use IntStream.of() method in place of for getting the IntStream from primitive int array.

For primitive array of double and long type, we can use DoubleStream and LongStream respectively. For example,


2. System.arraycopy()

System.arraycopy() provides convenient and very efficient way to copy arrays in Java. We can make use of this method to copy elements of given arrays into a newly allocated empty array.

We can also use Arrays.copyOf() along with System.arraycopy() as shown below:


3. Guava

Guava provides several utility class pertaining to primitives, like Ints for int, Floats for float, Doubles for double, Longs for long, Booleans for boolean, and so on.. Each utility class has concat() method that can combine specified primitive arrays into a single array.


4. Apache Commons Lang

Apache Commons Lang also provides static utility methods pertaining to int primitives, that are not already found in either Integer or Arrays. One such method is ArrayUtils.addAll() which can be used to join two arrays. This method is overloaded for all primitives types and object arrays.

Please note that all above methods will throw a NullPointerException if any specified array is null. We can easily add below snippet at the starting of each function to handle nulls.

Thanks for reading.

Work from anywhere on any device with a virtual cloud desktop by For more hosted Microsoft applications such as Exchange, SharePoint, Dynamics CRM, Project Server and more, try Apps4Rent.

Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂

Get great deals at Amazon

Leave a Reply

Notify of