【问题标题】:Groovy, how to iterate a list with an indexGroovy,如何使用索引迭代列表
【发布时间】: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
}

【问题讨论】:

    标签: arrays list groovy loops


    【解决方案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
    

    【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-10-20
      • 2014-10-04
      • 2014-05-29
      • 2018-09-21
      • 2010-09-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多