To split a list in Kotlin, you can use the subList
method or chunked
method for more complex splitting.
In this example,
numbers
with initial integer values.subList
method to create a sublist from the original list, specifying the start and end indices.subList
method returns a view of the specified range within the original list.fun main() {
val numbers = listOf(1, 2, 3, 4, 5, 6)
val sublist = numbers.subList(2, 5)
println("Sublist: $sublist")
}
Sublist: [3, 4, 5]
In this example,
numbers
with initial integer values.chunked
method to split the list into smaller lists of a specified size.chunked
method returns a list of lists, where each inner list contains elements from the original list.fun main() {
val numbers = listOf(1, 2, 3, 4, 5, 6, 7, 8)
val chunkedList = numbers.chunked(3)
println("Chunked list: $chunkedList")
}
Chunked list: [[1, 2, 3], [4, 5, 6], [7, 8]]
In this tutorial, we learned How to Split a List in Kotlin language with well detailed examples.