有没有带索引的.collect?我想做这样的事情:
def myList = [
[position: 0, name: 'Bob'],
[position: 0, name: 'John'],
[position: 0, name: 'Alex'],
]
myList.collect { index ->
it.position = index
}(即我想将position设置为一个值,该值将指示列表中的顺序)
发布于 2015-08-05 19:49:29
从Groovy2.4.0开始,在java.lang.Iterable中添加了一个withIndex()方法。
因此,以函数式方式(无副作用,不可变),它看起来像
def myList = [
[position: 0, name: 'Bob'],
[position: 0, name: 'John'],
[position: 0, name: 'Alex'],
]
def result = myList.withIndex().collect { element, index ->
[position: index, name: element["name"]]
}发布于 2012-10-25 04:15:16
稍微时髦一点的collectWithIndex版本:
List.metaClass.collectWithIndex = {body->
def i=0
delegate.collect { body(it, i++) }
}甚至是
List.metaClass.collectWithIndex = {body->
[delegate, 0..<delegate.size()].transpose().collect(body)
}发布于 2012-02-24 21:45:08
eachWithIndex可能会工作得更好:
myList.eachWithIndex { it, index ->
it.position = index
}使用collectX似乎没有必要,因为您只是修改了集合,而不是将其中的特定部分返回到新集合中。
https://stackoverflow.com/questions/9431723
复制相似问题