Kotlin List subList()
Syntax & Examples
Syntax of subList()
The syntax of List.subList() function is:
abstract fun subList(fromIndex: Int, toIndex: Int): List<E>
This subList() function of List returns a view of the portion of this list between the specified fromIndex (inclusive) and toIndex (exclusive). The returned list is backed by this list, so non-structural changes in the returned list are reflected in this list, and vice-versa.
✐ Examples
1 Example
In this example,
- We create a list named
list1
containing the elements'a', 'b', 'c', 'd', 'e'
. - We obtain a subList from
list1
starting at index1
(inclusive) and ending at index4
(exclusive) using the ListsubList(fromIndex: Int, toIndex: Int)
function. - The resulting subList contains the elements
'b', 'c', 'd'
. - We print the subList to standard output using the
println
function.
Kotlin Program
fun main(args: Array<String>) {
val list1 = listOf("a", "b", "c", "d", "e")
val subList1 = list1.subList(1, 4)
println(subList1)
}
Output
[b, c, d]
2 Example
In this example,
- We create a list named
list2
containing the integers10, 20, 30, 40, 50
. - We obtain a subList from
list2
starting at index2
(inclusive) and ending at index5
(exclusive) using the ListsubList(fromIndex: Int, toIndex: Int)
function. - The resulting subList contains the elements
30, 40, 50
. - We print the subList to standard output using the
println
function.
Kotlin Program
fun main(args: Array<String>) {
val list2 = listOf(10, 20, 30, 40, 50)
val subList2 = list2.subList(2, 5)
println(subList2)
}
Output
[30, 40, 50]
Summary
In this Kotlin tutorial, we learned about subList() function of List: the syntax and few working examples with output and detailed explanation for each example.