28

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?

breezymri
  • 3,447
  • 7
  • 28
  • 60
  • 1
    https://stackoverflow.com/questions/10117026/convert-iterator-to-arraylist tells you how to convert an iterator into a list in Java. It's trivial to do the same in Kotlin. – DPM Sep 08 '17 at 02:46

2 Answers2

46

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]
Aivean
  • 10,277
  • 24
  • 37
5

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()
andras
  • 2,707
  • 2
  • 24
  • 39