Kotlin List.subList() – Examples

Kotlin List.subList()

The Kotlin List.subList(fromIndex, toIndex) function returns a view of the portion of this list between the specified fromIndex (inclusive) and toIndex (exclusive).

Syntax

List.subList(fromIndex, toIndex)

Example 1

In this example,

  1. Take a list of strings.
  2. Specify fromIndex and toIndex.
  3. Get sub list of the above list, in the index range of [fromIndex, toIndex).

Program

fun main(args: Array<String>) {
    val list1 = listOf("a", "b", "c", "d", "c", "e")
    val fromIndex = 1
    val toIndex = 4
    val sublist = list1.subList(fromIndex, toIndex)
    print(sublist)
}

Output

[b, c, d]