想象一下,我有一个大的列表,我想分成更小的块进行处理:
def chunkSize = 10
def listSize = aBigList.size()
for(def i = 0; i < listSize; i += chunkSize) {
def startOfRange = i
def endOfRange = (listSize - 1) < (i + increment - 1) ? (listSize - 1) : (i + increment - 1) // There has got to be a better way!
def chunk = aBigList[startOfRange..endOfRange]
// do something with chunk
}
获取endOfRange
变量的代码是丑陋且非常常的,但是为了防止Index Out of Bounds
异常是必需的。有更好的方法吗?
答案 0 :(得分:4)
你不能使用collate吗?
def chunks = aBigList.collate( chunkSize )
如果没有,修复代码会给你类似的东西:
def chunkSize = 10
def listSize = aBigList.size()
for( i = 0; i < listSize; i += chunkSize ) {
def endOfRange = i + chunkSize - 1 >= aBigList.size() ? -1 : i + chunkSize - 1
def chunk = aBigList[ i..endOfRange ]
// do something with chunk
}
但是,只要aBigList
不是真正巨大的,整理可能就是可行的方法; - )