Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin iterator to list?

Tags:

kotlin

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?

like image 603
breezymri Avatar asked Sep 08 '17 02:09

breezymri


People also ask

How do you iterate a mutable list in Kotlin?

Mutable List Iterators. We can use the iterator() method provided by the MutableCollection interface. In addition to iterating over lists, this iterator also allows removing elements using the remove() method: fun iterateUsingIterator() { val iterator = cities.

What is iterable in Kotlin?

Iterators are useful when you need to process all the elements of a collection one-by-one, for example, print values or make similar updates to them. Iterators can be obtained for inheritors of the Iterable<T> interface, including Set and List , by calling the iterator() function.


2 Answers

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]
like image 92
Aivean Avatar answered Oct 08 '22 09:10

Aivean


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()
like image 4
andras Avatar answered Oct 08 '22 09:10

andras