This article explores different ways to partition a list into sublists of a given size in Kotlin. The last list in the resulting collection may contain fewer elements.

1. Using chunked() function

With Kotlin 1.2, we can use the chunked() function to split a list into a list of lists, each not exceeding the given size. It can be used as follows:

Download Code

Output:

[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15]]

2. Using windowed() function

Alternatively, we can use the windowed() library function starting with Kotlin 1.2. A typical invocation for this function would look like:

Download Code

Output:

[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15]]

3. Using subList() function

Before Kotlin 1.2, we can write custom logic to partition a list into equal-size chunks. The following solution uses a loop to iterate over the list and the subList() function to partition the list between starting and ending index.

Download Code

Output:

[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15]]

 
This is equivalent to the following code using the map() function:

Download Code

Output:

[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15]]

4. Using groupBy() function

Another option is to use the groupBy() function to perform the equivalent of a “group by” operation on the list elements. It groups the elements according to a classification function and returns the results in a map.

Download Code

Output:

[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15]]

 
The code can be simplified using a mutable counter like AtomicInteger:

Download Code

Output:

[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15]]

That’s all about partitioning a list into sublists of a given size in Kotlin.