arrayskotlinsequence

Kotlin Sequence to Array


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 Sequences. And toList().toArray() (toList().toIntArray()) creates an extra temporary list.


Solution

  • 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() }
    }