How to Concatenate Two Arrays in Java
Learn to concatenate two primitive arrays or objects arrays to create a new array consisting of the items from both arrays. We will learn to merge array items using simple for-loop, stream API and other utility classes.
Note that no matter which technique we use for merging the arrays, it always creates a new array of combined length of both arrays and then copies the items from both arrays into the new array, one at a time, in a loop. So the main difference between the various ways, discussed below, is code readability and ease of use.
1. Concatenating Arrays with ‘for loop’
Directly using the for-loop to merge the arrays is the most efficient in terms of performance. It does not create unnecessary temporary variables and objects.
We create a new array of combined length of two given arrays and then start putting items from both arrays into the new array in a loop. Theoretically, this method should give the best performance.
2. Using System.arraycopy()
Using arraycopy() is equivalent to using the for-loop. Here we delegate the task of copying the array items into a new array to the native function arraycopy() .
Performance-wise, arraycopy() method should perform on par with the for-loop method.
We can write a generic type method that can be used to merge the arrays holding the items of any object type.
3. Merging Arrrays with Stream.concat()
The stream.concat() method creates a lazily concatenated stream whose elements are all the elements of the first stream followed by all the elements of the second stream.
To obtain the streams, we convert the arrays into streams and then concat() to merge the streams. Later, we can collect the stream items into an array to complete the merge process.
We can use this technique to concatenate more than two arrays in a single statement.
To merge the array of primitives, we can directly use the following classes:
- IntStream
- LongStream
- DoubleStream
These classes provide the concat() methods specific to these primitives.
4. ArrayUtils from Apache Commons
We can use the 3rd part libraries that provide easy-to-use one-line methods for merging the arrays. They also provide the same level of performance as previous methods.
A similar API is ArrayUtils.addAll() that adds all the elements of the given arrays into a new array. Note that the returned array always returns a new array, even if we are merging two arrays and one of them is null .
5. Guava APIs
Guava APIs provide the following classes that we can use to merge arrays of primitives as well as arrays of object types.
- Ints.concat() : concatenates two int arrays.
- Longs.concat() : concatenates two long arrays.
- Doubles.concat() : concatenates two double arrays.
- ObjectArrays.concat() : concatenates two object type arrays.
6. Conclusion
In this tutorial, we learned to merge two arrays in Java. We learned to use the native Java APIs as well as the utility classes from the 3rd party libraries.
All the above methods will give almost the same level of performance for small arrays. For big arrays, it is recommended to do performance testing before finalizing the approach. However theoretically, using the for-loop and arraycopy() method should provide the best performance among all.
Как объединить два массива
В этой статье мы рассмотрим несколько способов объединения двух массивов. В зависимости от типа элементов (ссылочный или примитивный тип) массива и требований к быстродействию можно применить разные по краткости и удобочитаемости способы.
Объединения двух массивов с элементами ссылочного типа
Данным способом можно объединить массивы ссылочного типа (то есть не массивы с примитивами). Данный способ работает в Java 6 и выше.
Можно воспользоваться возможностями Java 8 и сделать объединение массивов с помощью стримов:
Объединения двух массивов с элементами любого типа
В отличие от предыдущего способа, здесь мы можем объединить массивы не только ссылочного типа, но и примитивного:
Объединение массивов с помощью ArrayUtils
Наиболее лаконичный способ объединить элементы двух массивов – это воспользоваться классов ArrayUtils из Commons Lang. Для этого сначала нужно подключить библиотеку в проект:
Исходный код
Заключение
В этой статье мы рассмотрели различные способы для объединения двух массивов.
Варианты объединения двух массивов в Java
В любом языке с долгой историей появляется то-ли фича то ли бага делать одну, вроде бы простую вещь можно несколькими способами. Возьмем тривиальную задачу: объединить два массива одного типа в один в java. И тут оказывается есть три способа как это сделать с разной степенью абстракции и со своими плюсами и минусами. Рассмотрим их.
Первый и самый короткий — это использовать старую добрую библиотечку Apache Commons Lang. И метод public static T[] addAll(T[] array1,T… array2).
Пример использования:
How to concatenate two arrays in Java
In this short article, you will learn about different ways to concatenate two arrays into one in Java.
Please enable JavaScript
Using A Loop
The simplest way to concatenate two arrays in Java is by using the for loop:
The above code snippet will output the following on the console:
Using System.arraycopy() Method
Another way of concatenating two arrays in Java is by using the System.arraycopy() method (works for both primitive and generic types), as shown below:
Here is the output of the above code:
Using Java 8 Stream
If you can using Java 8 or higher, it is also possible to use the Stream API to merge two arrays into one. Here is an example:
Here is the output:
Streams can also be used for non-primitive arrays like int[] :
Here is the output of the above code:
Using Apache Commons Lang
If you are already using the Apache Commons Lang library, just use the ArrayUtils. addAll() method to concatenate two arrays into one. This method works for both primitive as well as generic type arrays.
Let us have another example of primitive arrays:
Don’t forget to include the following dependency to your pom.xml file:
For a Gradle project, add the following dependency to your build.gradle file:
✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.