ribesg
03/05/2017, 9:29 AMfun <T> List<T>.batched(batchSize: Int): List<List<T>> {
check(batchSize > 0) { "Invalid value for parameter 'batchSize': $batchSize (should be greater than 0)" }
val batchAmount = (size + batchSize - 1) / batchSize
val result = List<MutableList<T>>(batchAmount) { ArrayList(batchSize) }
var index = 0
forEach { result[index++ / batchSize].add(it) }
return result
}
You seem to care about optimization, so note than when called on a LinkedList
, your implementation does a O(N) get
call on line 13mg6maciej
03/05/2017, 10:18 AMbatch
could be added to #C0B8Q383C too.ribesg
03/05/2017, 10:19 AMmg6maciej
03/05/2017, 10:21 AMgaetan
03/05/2017, 10:21 AMsublist
in that case.