Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 237
Shreck Ye Avatar asked Apr 28 '19 05:04

Shreck Ye


2 Answers

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() }
}
like image 134
yole Avatar answered Nov 13 '22 05:11

yole


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() }
}
like image 39
Florian Reisinger Avatar answered Nov 13 '22 07:11

Florian Reisinger