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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9522897/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 01:47:55  来源:igfitidea点击:

Groovy, how to iterate a list with an index

arrayslistgroovyloops

提问by raffian

With all the shorthand ways of doing things in Groovy, there's got to be an easier way to iterate a list while having access to an iteration index.

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

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

Is there no implicit index in a basic forloop?

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

for( item in list){
    println item       
    println index
}

回答by ataylor

You can use eachWithIndex:

您可以使用eachWithIndex

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

With Groovy 2.4 and newer, you can also use the indexed()method. This can be handy to access the index with methods like collect:

对于 Groovy 2.4 和更新版本,您还可以使用该indexed()方法。这可以方便地使用以下方法访问索引collect

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

回答by R Tiwari

Try this if you want to start index 1.

如果您想启动索引 1,请尝试此操作。

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