Kotlin迭代器要列出? [英] Kotlin iterator to list?
本文介绍了Kotlin迭代器要列出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个来自 fieldNames :
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")
}
显然,上面的代码不起作用,因为xs
不能像这样对Iterator建立索引.我试图查看是否可以通过mm.toList()
将迭代器转换为列表,但是不存在.
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.
我该如何实现?
推荐答案
可能最简单的方法是先将迭代器转换为Sequence
,然后再转换为List
:
Probably the easiest way is to convert iterator to Sequence
first and then to List
:
listOf(1,2,3).iterator().asSequence().toList()
结果:
[1, 2, 3]
这篇关于Kotlin迭代器要列出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文