Skip to content

Instantly share code, notes, and snippets.

@timyates
Created February 22, 2012 15:52
Show Gist options
  • Select an option

  • Save timyates/1885656 to your computer and use it in GitHub Desktop.

Select an option

Save timyates/1885656 to your computer and use it in GitHub Desktop.
What's new in Groovy 1.8.6 -- the collate method
def list = 1..10
def gridList = list.collate( 3 ).collate( 2 )
assert gridList == [ [ [1, 2, 3], [4, 5, 6] ],
[ [7, 8, 9], [10] ] ]
def items = [ 'ham', 30, 'cheese', 20, 'steak', 95 ]
def itemMap = items.collate( 2 ).collectEntries()
assert itemMap == [ ham:30, cheese:20, steak:95 ]
def list = 1..10
def listInFours2 = list.collate( 4, false )
// Notice the [ 9, 10 ] remainder has been dropped
assert listInFours2 == [ [ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ] ]
def list = 1..10
def listInFours = list.collate( 4 )
assert listInFours == [ [ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ], [ 9, 10 ] ]
def mph = [ 10, 26, 30, 32, 27, 14, 19, 22, 40, 14 ]
def window = mph.collate( 3, 1, false )
assert window == [ [10, 26, 30],
[26, 30, 32],
[30, 32, 27],
[32, 27, 14],
[27, 14, 19],
[14, 19, 22],
[19, 22, 40],
[22, 40, 14] ]
def windowAvg = window*.sum()*.intdiv( 3 )
assert windowAvg == [22, 29, 29, 24, 20, 18, 27, 25]
def range = 1..20
def (odds,evens) = range.collate( 2 ).transpose()
assert odds == (1..19).step( 2 ) // odd numbers 1 - 19
assert evens == (2..20).step( 2 ) // even numbers 2 - 20
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment