加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

数组 – Groovy,如何用索引迭代列表

发布时间:2020-12-14 16:38:51 所属栏目:大数据 来源:网络整理
导读:使用Groovy中所做的所有简单的方法,在访问一个迭代索引时,必须有一个更简单的方法来遍历列表。 for(i in 0 .. list.size()-1) { println list.get(i)} 在一个基本的for循环中没有隐含的索引? for( item in list){ println item println index} 解决方法
使用Groovy中所做的所有简单的方法,在访问一个迭代索引时,必须有一个更简单的方法来遍历列表。

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

在一个基本的for循环中没有隐含的索引?

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

解决方法

您可以使用 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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读