Merge two or more arrays in Kotlin
This article explores different ways to merge multiple arrays in Kotlin into a single array. The solution should maintain the original order of elements in individual arrays.
1. Using Plus Operator
A simple and fairly efficient solution to combine two arrays in Kotlin is with the plus operator. This is demonstrated below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
inline fun<reified T> merge(vararg arrays: Array<T>): Array<T?> { var result: Array<T?> = arrayOfNulls(0); for (array in arrays) { result += array; } return result } fun main() { val first: Array<String> = arrayOf("A", "B") val second: Array<String> = arrayOf("C", "D") val third: Array<String> = arrayOf("E", "F") val result = merge(first, second, third) println(result.contentToString()) // [A, B, C, D, E, F] } |
An equivalent way is to use the plus() function.
|
1 2 3 4 5 6 7 |
inline fun<reified T> merge(vararg arrays: Array<T>): Array<T?> { var result: Array<T?> = arrayOfNulls(0); for (array in arrays) { result = result.plus(array); } return result } |
2. Using copyOf() with System.arraycopy() function
The idea is to allocate enough memory to the new array for accommodating all elements present in all arrays using the copyOf() function. Then use System.arraycopy() to copy the given arrays into the new array, as shown below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
fun <T> merge(vararg arrays: Array<T>): Array<T?>? { var totalSize = 0 for (array in arrays) { totalSize += array.size } var dest: Array<T?>? = null var destPos = 0 for (array in arrays) { if (dest == null) { dest = array.copyOf(totalSize) destPos = array.size } else { System.arraycopy(array, 0, dest, destPos, array.size) destPos += array.size } } return dest } fun main() { val first: Array<String> = arrayOf("A", "B") val second: Array<String> = arrayOf("C", "D") val third: Array<String> = arrayOf("E", "F") val result = merge(first, second, third) println(result?.contentToString()) // [A, B, C, D, E, F] } |
3. Using MutableList
We can also use a MutableList to merge multiple arrays in Kotlin, as shown below. This approach uses the addAll() function:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
inline fun<reified T> merge(vararg arrays: Array<T>): Array<T> { val list: MutableList<T> = ArrayList() for (array in arrays) { list.addAll(array.map { i -> i }) } return list.toTypedArray() } fun main() { val first: Array<String> = arrayOf("A", "B") val second: Array<String> = arrayOf("C", "D") val third: Array<String> = arrayOf("E", "F") val result = merge(first, second, third) println(result.contentToString()) // [A, B, C, D, E, F] } |
That’s all about merging multiple arrays in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)