Kotlin List.subList() Function

The Kotlin List.subList() function returns a part of the list with elements whose index is in between the specified fromIndex (inclusive) and until toIndex (exclusive).

Mathematically, the range of index considered would be [fromIndex, toIndex) of the original list.

Syntax of List.subList()

The syntax of List.subList() function is

subList(fromIndex, toIndex)
ParameterDescription
fromIndexRequired. The index from which elements of this list will be considered in the result.
toIndexRequired. The index until which elements of this list will be considered in the result.

Return Value

List.subList() function returns a new list with the elements selected from the index range specified by fromIndex and toIndex.

Example 1: Get Sub-list of a List

In this example, we will take a list of string elements, and find the sub list of this list using List.subList() function.

Kotlin Program

fun main(args: Array<String>) {
    val list1 = listOf("ab", "bc", "cd", "de", "ef", "fg", "gh")
    val fromIndex = 2
    val toIndex = 5
    val result = list1.subList(fromIndex, toIndex)
    print(result)
}

Output

[cd, de, ef]

Since fromIndex is 2, starting index will be 2 and since the toIndex is 5, ending index would be 4. So the elements with index 2, 3 and 4 are considered for the return value.

Example 2: List.subList() – fromIndex/toIndex out of Range

In this example, we will try to provide toIndex argument with a value such that this index is out of range for the given list.

Kotlin Program

fun main(args: Array<String>) {
    val list1 = listOf("ab", "bc", "cd", "de", "ef", "fg", "gh")
    val fromIndex = 2
    val toIndex = 10
    val result = list1.subList(fromIndex, toIndex)
    print(result)
}

Output

Exception in thread "main" java.lang.IndexOutOfBoundsException: toIndex = 10
	at java.base/java.util.AbstractList.subListRangeCheck(AbstractList.java:507)
	at java.base/java.util.AbstractList.subList(AbstractList.java:497)
	at HelloWorldKt.main(HelloWorld.kt:5)

Conclusion

In this Kotlin Tutorial, we learned how to find the sublist of a given list based on index range, using Kotlin List.subList() function.