Skip to content
DeveloperMemos

Chunking Lists in Kotlin

Kotlin, Lists, Chunking1 min read

One of the features of Kotlin is its ability to easily manipulate collections of data, including the ability to chunk a list into smaller lists. This can be useful when working with large lists of data that need to be processed or displayed in a specific way.

To chunk a list in Kotlin, we can use the chunked() function. This function takes a list and an integer n as arguments, and returns a list of lists, where each sublist contains n elements from the original list. For example, if we have a list of integers and we want to chunk it into sublists of size 3, we can use the chunked() function like this:

1val numbers = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
2val chunkedNumbers = numbers.chunked(3)

In this example, chunkedNumbers will be a list of lists, with each sublist containing 3 elements from the original list of numbers. The first sublist will contain the elements 1, 2, 3, the second sublist will contain the elements 4, 5, 6, and so on.

Alternatively, we can use the chunked() function with a transform lambda to apply a specific transformation to each chunk of the list. This can be useful if we want to perform some operation on each chunk, such as sorting the elements or filtering out certain values. For example, we can use the chunked() function like this to sort each chunk of the list:

1val numbers = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
2val chunkedNumbers = numbers.chunked(3) { it.sorted() }

In this example, chunkedNumbers will be a list of lists, with each sublist containing 3 elements from the original list of numbers. However, the elements in each sublist will be sorted in ascending order. The first sublist will contain the elements 1, 2, 3, the second sublist will contain the elements 4, 5, 6, and so on.

In conclusion, the chunked() function in Kotlin makes it easy to divide a list into smaller lists, or "chunks". This can be useful when working with large lists of data that need to be processed or displayed in a specific way. By using the chunked() function, we can easily manipulate collections of data in Kotlin to achieve the desired results.