breezymri
breezymri

Reputation: 4343

Kotlin iterator to list?

I have an iterator of strings from fieldNames of JsonNode:

val mm = ... //JsonNode
val xs = mm.fieldNames()

I want to loop over the fields while keeping count, something like:

when mm.size() {
  1 -> myFunction1(xs[0])
  2 -> myFunction2(xs[0], xs[1])
  3 -> myFunction3(xs[0], xs[1], xs[2])
  else -> print("invalid")
}

Obviously the above code does not work as xs the Iterator cannot be indexed like so. I tried to see if I can convert the iterator to list by mm.toList() but that does not exist.

How can I achieve this?

Upvotes: 45

Views: 25336

Answers (3)

Robert
Robert

Reputation: 81

You can turn an Iterator into an Iterable using Iterable { iterator } on which you can then call toList():

Iterable { listOf(1,2,3).iterator() }.toList() // [1, 2, 3]

Upvotes: 8

andras
andras

Reputation: 3645

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

Upvotes: 4

Aivean
Aivean

Reputation: 10882

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]

Upvotes: 66

Related Questions