ubiquibacon
ubiquibacon

Reputation: 10667

Groovy way to find valid end of a range

Imagine I have a big list I want to split up in to smaller chunks for processing:

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
}

The code for getting the endOfRange variable is ugly and non-groovy, but is required in order to prevent an Index Out of Bounds exception. Is there a better way to do this?

Upvotes: 1

Views: 71

Answers (1)

tim_yates
tim_yates

Reputation: 171144

Can't you use collate?

def chunks = aBigList.collate( chunkSize )

If not, fixing your code gives you something like:

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
}

But collate is probably the way to go so long as aBigList isn't truly enormous ;-)

Upvotes: 4

Related Questions