Split a list in Kotlin
This article explores different ways to split a list in Kotlin.
1. Using subList() function
The idea is to use the subList() function that returns a view of the list between the specified indexes. Note that this list backs the returned list.
|
1 2 3 4 5 6 7 8 9 10 11 |
fun main() { val list = listOf(1, 2, 3, 4, 5) val n = list.size // get the size of the list val first = list.subList(0, (n + 1) / 2) val second = list.subList((n + 1) / 2, n) println(first) println(second) } |
2. Using chunked() function
The preferred approach to split the list where each sublist does not exceed the given size is to use the chunked() function. Note that the last list may have fewer elements than the given size.
|
1 2 3 4 5 6 7 |
fun main() { val list = (0..9).toList() val size = 3 var subLists: List<List<Int>> = list.chunked(size) subLists.forEach { println(it) } } |
3. Using windowed() function
Another simple approach is to use the windowed() function, which returns a list of the given size sliding along this collection with the given step.
|
1 2 3 4 5 6 7 |
fun main() { val list = (0..9).toList() val size = 3 var subLists: List<List<Int>> = list.windowed(size=size, step=size, partialWindows=true) subLists.forEach { println(it) } } |
That’s all about splitting a list in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)