How to 'Slice' a Collection in Groovy

I have a collection of objects that I want to break up into a collection of collections, where each sequential group of 3 elements is in one collection. For example, if I have

def l = [1,4,2,4,5,9]

I want to turn this into:

def r = [[1,4,2], [4,5,9]]

I'm doing it now by iterating over the collection and breaking it up.. but I then need to pass those 'groups' into a parallelized function that processes them.. It would be nice to eliminate this O(n) pre-processing work and just say something like

l.slice(3).collectParallel { subC -> process(subC) }

I've found the step method on the Range class, but it looks like that only acts on the indices. Any clever ideas?

Update: I don't think this is a duplicate of the referenced link, although it's very close. As suggested below, it's more of the iterator-type thing I'm looking for.. the sub-collections will then be passed into a GPars collectParallel. Ideally I wouldn't need to allocate an entire new collection.

12
задан Bobby 3 May 2011 в 19:14
поделиться