If you have a large collection and you may want to break the elements of the list in batches or chuncks for further processing. This example we will show how to partition a list into sublists using groovy. In a groovy list collate()
exists to split a list into sub-lists of a specified size. This feature also exists for collections and iterables. There are various overloaded methods so be sure to look into the documentation. In a comparable example we demonstrate how to split an arraylist into sublists in java.
Collate
@Test
void partition_list() {
def list = ["a", "b", "c", "d", "e"]
assert [["a", "b"], ["c", "d"], ["e"]] == list.collate(2)
}
Collate keep remainder
@Test
void partition_keep_remainder() {
def list = ["a", "b", "c", "d", "e"]
assert [["a", "b"], ["c", "d"]] == list.collate(2, false)
}