如何在Groovy的eachWithIndex方法中指定索引的起始值?

时间:2012-01-11 15:12:43

标签: loops groovy closures

当使用Groovy的eachWithIndex方法时,索引值从0开始,我需要从1开始。我该怎么做?

4 个答案:

答案 0 :(得分:7)

索引始终从0

开始

您的选择是:

1)向索引添加偏移量:

int offs = 1
list.eachWithIndex { it, idx ->
  println "$it @ pos ${idx + offs}"
}

2)使用eachWithIndex之外的其他内容(即:将原始列表中从1开始的整数列表转置,然后循环显示)

3)你也可以使用默认参数来破解这种事情...如果我们传递eachWithIndex一个带有3个参数的闭包(eachWithIndex期待的两个参数和第三个参数默认值index + 1):

[ 'a', 'b', 'c' ].eachWithIndex { item, index, indexPlusOne = index + 1 ->
  println "Element $item has position $indexPlusOne"
}

我们将提供输出:

Element a has position 1
Element b has position 2
Element c has position 3

答案 1 :(得分:3)

我根本不会使用eachWithIndex,带有.indexed(1)的for循环会更优雅/可读:

for (item in ['a','b','c','d','e'].indexed(1)) {
  println("element $item.key = $item.value")
}

输出:

element 1 = a
element 2 = b
element 3 = c
element 4 = d
element 5 = e

告诫 - 索引(n)仅在Groovy 2.4.0及更高版本中可用

答案 2 :(得分:0)

你也可以使用一些元编程hackery:

def eachWithMyIndex = { init, clos ->
    delegate.eachWithIndex { it, idx -> clos(it, idx + init) }
}
List.metaClass.eachWithMyIndex = eachWithMyIndex    

[1,2,3].eachWithMyIndex(10) {n, idx ->  println("element $idx = $n") }

给出输出:

element 10 = 1
element 11 = 2
element 12 = 3

答案 3 :(得分:0)

使用Range怎么样?

def offset = 1
def arr = [1,2,3,4,5]
def len = arr.size() - 1
arr[offset..len].eachWithIndex{n,i -> println "${i+offset}:$n"}