Combine two arrays of different types in Kotlin
This article explores different ways to combine two arrays of different types into an object array in Kotlin. The new object new array should contain all the first array elements, followed by all the elements second array.
1. Using Stream.concat()
function
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
import java.util.* import java.util.stream.Stream fun <T, U> combine(first: Array<T>?, second: Array<U>?): Array<Any?>? { return Stream.concat(Arrays.stream(first), Arrays.stream(second)) .toArray() } fun main() { val first = arrayOf(1, 2, 3) val second = arrayOf('A', 'B', 'C') val joined = combine(first, second) println(joined?.contentToString()) // [1, 2, 3, A, B, C] } |
2. Using System.arraycopy()
function
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
fun <T, U> combine(first: Array<T>, second: Array<U>): Array<Any?>? { val obj = arrayOfNulls<Any>(first.size + second.size) System.arraycopy(first, 0, obj, 0, first.size) System.arraycopy(second, 0, obj, first.size, second.size) return obj } fun main() { val first = arrayOf(1, 2, 3) val second = arrayOf('A', 'B', 'C') val joined = combine(first, second) println(joined?.contentToString()) // [1, 2, 3, A, B, C] } |
3. Using MutableList
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
fun <T, U> combine(first: Array<T>, second: Array<U>): Array<Any> { val list: MutableList<Any> = first.map { i -> i as Any }.toMutableList() list.addAll(second.map { i -> i as Any }) return list.toTypedArray() } fun main() { val first = arrayOf(1, 2, 3) val second = arrayOf('A', 'B', 'C') val joined = combine(first, second) println(joined.contentToString()) // [1, 2, 3, A, B, C] } |
The above code is short for the following:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
fun <T, U> combine(first: Array<T>, second: Array<U>): Array<Any> { val list: MutableList<Any> = ArrayList(); list.addAll(first.map { i -> i as Any }) list.addAll(second.map { i -> i as Any }) return list.toTypedArray() } fun main() { val first = arrayOf(1, 2, 3) val second = arrayOf('A', 'B', 'C') val joined = combine(first, second) println(joined.contentToString()) // [1, 2, 3, A, B, C] } |
That’s all about combining two arrays of different types in Kotlin.
Also See:
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 :)