Skip to content
DeveloperMemos

Merging Two Arrays in Kotlin

Kotlin, Arrays1 min read

Merging two arrays is a common operation in programming. It involves combining two arrays into a single array that contains all the elements of both arrays. In Kotlin, there are several ways to merge two arrays. In this article, we will explore some of them.

Using the plus() function

One way to merge two arrays in Kotlin is to use the plus() function. This function returns a new array that contains all the elements of the first array followed by all the elements of the second array.

1val arr1 = arrayOf(1, 2, 3)
2val arr2 = arrayOf(4, 5, 6)
3
4val mergedArr = arr1.plus(arr2)
5
6println(mergedArr.contentToString()) // Output: [1, 2, 3, 4, 5, 6]

Using the union() function

Another way to merge two arrays in Kotlin is to use the union() function. This function returns a new set that contains all the distinct elements of both arrays.

1val array1 = arrayOf("apple", "banana", "orange")
2val array2 = arrayOf("pear", "kiwi", "orange")
3
4val mergedSet = array1.asIterable().union(array2.asIterable())
5
6mergedSet.forEach { println(it) }

Note that the union() function returns a set, not an array. To convert the set into an array, you can use the toTypedArray() function.

Using the plusAssign() operator

Finally, you can also merge two arrays by using the += or plusAssign() operator. This operator adds all the elements of the second array to the first array.

1var arr1 = arrayOf(1, 2, 3)
2var arr2 = arrayOf(4, 5, 6)
3
4arr1 += arr2
5
6println(arr1.contentToString()) // Output: [1, 2, 3, 4, 5, 6]

In conclusion, merging two arrays in Kotlin can be done in several ways, depending on your specific needs. Whether you need to concatenate two arrays, create a set with distinct elements, or simply add one array to another, Kotlin provides a variety of options to choose from.