要列表的Kotlin迭代器?

eivgtgni  于 2022-12-04  发布在  Kotlin
关注(0)|答案(3)|浏览(148)

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

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

我想循环遍历字段,同时保持计数,如下所示:

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

显然上面的代码不能像xs那样工作,迭代器不能像这样被索引。我试图看看我是否可以通过mm.toList()将迭代器转换为列表,但这并不存在。
我如何才能做到这一点?

2eafrhcq

2eafrhcq1#

最简单的方法可能是先将迭代器转换为Sequence,然后再转换为List

listOf(1,2,3).iterator().asSequence().toList()

实验结果:

[1, 2, 3]
b4lqfgs4

b4lqfgs42#

我会跳过转换到序列,因为它只有几行代码。

fun <T> Iterator<T>.toList(): List<T> =
    ArrayList<T>().apply {
        while (hasNext())
            this += next()
    }

更新:
但是请记住,追加到ArrayList的性能不高,因此对于较长的列表,最好使用以下代码或accepted answer

fun <T> Iterator<T>.toList(): List<T> =
        LinkedList<T>().apply {
            while (hasNext())
                this += next()
        }.toMutableList()
wsxa1bj1

wsxa1bj13#

可以使用Iterable { iterator }Iterator转换为Iterable,然后在Iterable { iterator }上调用toList()

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

相关问题