Groovy,如何使用索引迭代列表

Posted

技术标签:

【中文标题】Groovy,如何使用索引迭代列表【英文标题】:Groovy, how to iterate a list with an index 【发布时间】:2012-03-20 08:13:03 【问题描述】:

使用 Groovy 中的所有速记方式,必须有一种更简单的方法来迭代列表,同时访问迭代索引。

for(i in 0 .. list.size()-1) 
   println list.get(i)

基本for 循环中没有隐式索引吗?

for( item in list)
    println item       
    println index

【问题讨论】:

【参考方案1】:

你可以使用eachWithIndex:

list.eachWithIndex  item, index ->
    println item
    println index

对于 Groovy 2.4 和更高版本,您还可以使用 indexed() 方法。这可以很方便地使用 collect 之类的方法访问索引:

def result = list.indexed().collect  index, item ->
    "$index: $item"

println result

【讨论】:

很好的答案,我在哪里可以找到像 eachWithIndex 这样的闭包以及它们采用的参数类型? 我从这里开始:groovy.codehaus.org/GDK+Extensions+to+Object 和 groovy.codehaus.org/JN1015-Collections【参考方案2】:

如果你想开始索引 1,试试这个。

[ 'rohit', 'ravi', 'roshan' ].eachWithIndex  name, index, indexPlusOne = index + 1 ->
    println "Name $name has position $indexPlusOne"

【讨论】:

以上是关于Groovy,如何使用索引迭代列表的主要内容,如果未能解决你的问题,请参考以下文章