Kotlin序列至阵列

Shr*_* Ye 3 arrays escaping stream kotlin java-stream

如何在Kotlin中有效地将转换SequenceArray(或原始数组,如IntArray)?

我发现没有toArray()用于Sequences的方法。和toList().toArray()toList().toIntArray())创建一个额外的临时列表。

yol*_*ole 6

没有toArray()方法,因为与列表不同,序列不允许找出其中包含多少个元素(实际上可以是无限个),因此无法分配正确大小的数组。

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() }
}
Run Code Online (Sandbox Code Playgroud)