Kotlin iterator to list?
Probably the easiest way is to convert iterator to Sequence
first and then to List
:
listOf(1,2,3).iterator().asSequence().toList()
result:
[1, 2, 3]
I would skip the conversion to sequence, because it is only a few lines of code.
fun <T> Iterator<T>.toList(): List<T> =
ArrayList<T>().apply {
while (hasNext())
this += next()
}
Update:
Please keep in mind though, that appending to an ArrayList
is not that performant, so for longer lists, you are better off with the following, or with the accepted answer:
fun <T> Iterator<T>.toList(): List<T> =
LinkedList<T>().apply {
while (hasNext())
this += next()
}.toMutableList()