https://kotlinlang.org logo
#announcements
Title
# announcements
r

ribesg

03/05/2017, 9:29 AM
@mg6maciej Here's what I did, in Kotlin 1.1:
Copy code
fun <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 13
👍 1
m

mg6maciej

03/05/2017, 10:18 AM
Yes. Your and @gaetan implementations are superior to mine. If I cared about optimizations in my case, I'd choose one of them.
batch
could be added to #stdlib too.
r

ribesg

03/05/2017, 10:19 AM
Based on my own tests I can say that @gaetan's solution is orders of magnitude better
m

mg6maciej

03/05/2017, 10:21 AM
Yes, both in terms of speed and memory use. sublist is backed by original list.
g

gaetan

03/05/2017, 10:21 AM
As a personal rule, I tend to use existing functions that are generally highly optimized.
sublist
in that case.
4 Views