。
Map.metaClass.partition = { size ->
def rslt = delegate.inject( [ [:] ] ) { ret, elem ->
( ret.last() << elem ).size() >= size ? ret << [:] : ret
}
rslt.last() ? rslt : rslt[ 0..-2 ]
}
因此,如果你照此图:
def origMap = [1: a , 2: b , 3: c , 4: d , 5: e , 6: f ]
下列所有主张均通过:
assert [ [1: a ], [2: b ], [3: c ], [4: d ], [5: e ], [6: f ] ] == origMap.partition( 1 )
assert [ [1: a , 2: b ], [3: c , 4: d ], [5: e , 6: f ] ] == origMap.partition( 2 )
assert [ [1: a , 2: b , 3: c ], [4: d , 5: e , 6: f ] ] == origMap.partition( 3 )
assert [ [1: a , 2: b , 3: c , 4: d ], [5: e , 6: f ] ] == origMap.partition( 4 )
assert [ [1: a , 2: b , 3: c , 4: d , 5: e ], [6: f ] ] == origMap.partition( 5 )
assert [ [1: a , 2: b , 3: c , 4: d , 5: e , 6: f ] ] == origMap.partition( 6 )
或作为<代码>Category (为避免在<代码>Map上添加任何内容:
class MapPartition {
static List partition( Map delegate, int size ) {
def rslt = delegate.inject( [ [:] ] ) { ret, elem ->
( ret.last() << elem ).size() >= size ? ret << [:] : ret
}
rslt.last() ? rslt : rslt[ 0..-2 ]
}
}
然后,如果你需要这一功能,你可以简单地读到<条码>。 a. 同类:
use( MapPartition ) {
assert [ [1: a ], [2: b ], [3: c ], [4: d ], [5: e ], [6: f ] ] == origMap.partition( 1 )
assert [ [1: a , 2: b ], [3: c , 4: d ], [5: e , 6: f ] ] == origMap.partition( 2 )
assert [ [1: a , 2: b , 3: c ], [4: d , 5: e , 6: f ] ] == origMap.partition( 3 )
assert [ [1: a , 2: b , 3: c , 4: d ], [5: e , 6: f ] ] == origMap.partition( 4 )
assert [ [1: a , 2: b , 3: c , 4: d , 5: e ], [6: f ] ] == origMap.partition( 5 )
assert [ [1: a , 2: b , 3: c , 4: d , 5: e , 6: f ] ] == origMap.partition( 6 )
}