Kotlin迭代器列出?

bre*_*mri 18 kotlin

我有一个来自fieldNames的字符串迭代器JsonNode:

val mm = ... //JsonNode
val xs = mm.fieldNames()
Run Code Online (Sandbox Code Playgroud)

我想在保持计数的同时循环遍历字段,例如:

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

显然上面的代码不起作用,因为xsIterator不能像这样索引.我试图看看我是否可以将迭代器转换为list by mm.toList()但不存在.

我怎样才能做到这一点?

Aiv*_*ean 24

可能最简单的方法是将迭代器转换为Sequence第一个然后转换为List:

listOf(1,2,3).iterator().asSequence().toList()
Run Code Online (Sandbox Code Playgroud)

结果:

[1, 2, 3]
Run Code Online (Sandbox Code Playgroud)


小智 7

您可以将 an 转换IteratorIterableusing Iterable { iterator },然后可以调用toList()

Iterable { listOf(1,2,3).iterator() }.toList() // [1, 2, 3]
Run Code Online (Sandbox Code Playgroud)