How to efficiently convert a Sequence
to an Array
(or a primitive array, like IntArray
) in Kotlin?
I found that there are no toArray()
methods for Sequence
s. And toList().toArray()
(toList().toIntArray()
) creates an extra temporary list.
There are no toArray()
methods because, unlike a list, a sequence does not allow to find out how many elements it contains (and it can actually be infinite), so it's not possible to allocate an array of the correct size.
If you know something about the sequence in your specific case, you can write a more efficient implementation by allocating an array and copying the elements from the sequence to the array manually. For example, if the size is known, the following function can be used:
fun Sequence<Int>.toIntArray(size: Int): IntArray {
val iter = iterator()
return IntArray(size) { iter.next() }
}
I would like to add a version for Sequence<T>
. Using the refied T (which requires the function to be inline) to create an array of the correct type, which would not be posible in Java :D
inline fun <reified T> Sequence<T>.toArray(size: Int): Array<T> {
val iter = iterator()
return Array(size) { iter.next() }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With