How to use for loop or any other loop to loop a list while taking specified number of items

Viewed 30

I have a list of vehicle makes, while the list is so large and I want to store it in room database in android. The app may crash while performing this operation. I want to loop through the list and take some chunks of items and to store to database. For example for each loop I take 20 items until the list is empty. How do I achieve this in Kotlin or any other suggestion that can work efficiently.

1 Answers

You don't say if you care in what order you want to remove the list items. If you don't care, then the following code shows how you can achieve it. Notice that the original list must be mutable for the remove() operation to work

val CHUNK_SIZE = 20
val vehicles = (0..177).map { "Car ${it}" }.toMutableList()

val carListIterator = vehicles.iterator()
val removalChunk = mutableListOf<String>()
while(carListIterator.hasNext()) {
    removalChunk.add(carListIterator.next())
    carListIterator.remove() // this removes the element that was just returned
    if(removalChunk.size >= CHUNK_SIZE || !carListIterator.hasNext()) {
        //store chunk elsewhere
        println("Storing: ${removalChunk.joinToString()}")
        removalChunk.clear()
    }
}
Related