The subList
function in Kotlin is used to create a view of a specified range within a list. This function belongs to the List
interface in the Kotlin standard library and allows you to work with a portion of the list without modifying the original list.
Table of Contents
- Introduction
subList
Function Syntax- Understanding
subList
- Examples
- Basic Usage
- Modifying the Sublist
- Using
subList
in a Real-World Scenario
- Conclusion
Introduction
The subList
function provides a way to create a view of a specified range within a list, enabling you to work with a subset of the list elements. This is particularly useful for operations that need to be performed on a segment of the list.
subList Function Syntax
The syntax for the subList
function is as follows:
fun <T> List<T>.subList(fromIndex: Int, toIndex: Int): List<T>
Parameters:
fromIndex
: The start index (inclusive) of the sublist.toIndex
: The end index (exclusive) of the sublist.
Returns:
- A view of the specified range within the list.
Understanding subList
The subList
function returns a view of the portion of this list between the specified fromIndex
, inclusive, and toIndex
, exclusive. The returned list is backed by the original list, so changes in the sublist are reflected in the original list.
Examples
Basic Usage
To demonstrate the basic usage of subList
, we will create a sublist from an existing list.
Example
fun main() {
val numbers = listOf(1, 2, 3, 4, 5, 6, 7)
val subList = numbers.subList(2, 5)
println("Original list: $numbers")
println("Sublist: $subList")
}
Output:
Original list: [1, 2, 3, 4, 5, 6, 7]
Sublist: [3, 4, 5]
Modifying the Sublist
This example shows how modifications to the sublist are reflected in the original list.
Example
fun main() {
val numbers = mutableListOf(1, 2, 3, 4, 5, 6, 7)
val subList = numbers.subList(2, 5)
println("Original list: $numbers")
println("Sublist: $subList")
subList[0] = 99
println("Modified sublist: $subList")
println("Modified original list: $numbers")
}
Output:
Original list: [1, 2, 3, 4, 5, 6, 7]
Sublist: [3, 4, 5]
Modified sublist: [99, 4, 5]
Modified original list: [1, 2, 99, 4, 5, 6, 7]
Using subList
in a Real-World Scenario
This example demonstrates how to use subList
in a real-world scenario, such as processing chunks of data.
Example
fun main() {
val data = listOf("A", "B", "C", "D", "E", "F", "G", "H")
val chunkSize = 3
val chunks = mutableListOf<List<String>>()
for (i in data.indices step chunkSize) {
val end = (i + chunkSize).coerceAtMost(data.size)
chunks.add(data.subList(i, end))
}
println("Data chunks: $chunks")
}
Output:
Data chunks: [[A, B, C], [D, E, F], [G, H]]
Conclusion
The subList
function in Kotlin's List
interface is a useful method for creating a view of a specified range within a list. It allows you to work with portions of a list efficiently and can be used in various scenarios, including data processing and segmenting lists for operations.
Comments
Post a Comment
Leave Comment