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?
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.
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.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With