zt
03/20/2024, 4:52 AMSam
03/20/2024, 8:48 AMwithIndex()
on your original list of objects. That will tag each one with its position in the original list. Then you can group and process the elements however you want, storing this "original index" alongside each item as you go. Once you have all your results, you can use that stored index to reconstruct the original list order.Sam
03/20/2024, 8:49 AMfun getResults(inputs: List<Input>): List<Output> {
val outputs = arrayOfNulls<Output>(inputs.size)
val inputsByType: Map<Input.Type, List<IndexedValue<Input>>> =
inputs.withIndex().groupBy { it.value.type }
for ((type, items) in inputsByType) {
for (batch in items.chunked(batchSize)) {
val results = api.getItemBatch(type, batch.map { it.value })
for ((request, result) in batch zip results) {
outputs[request.index] = result
}
}
}
return outputs.requireNoNulls().asList()
}
Sam
03/20/2024, 8:49 AMoutputs
an Array
means it should even be safe to add concurrency if you wantSam
03/20/2024, 8:50 AM