Kotlin List indexOfLast()
Syntax & Examples
Syntax of List.indexOfLast()
There are 2 variations for the syntax of List.indexOfLast() extension function. They are:
1.
fun <T> List<T>.indexOfLast(predicate: (T) -> Boolean): IntThis extension function returns index of the last element matching the given predicate, or -1 if the list does not contain such element.
2.
fun <T> Iterable<T>.indexOfLast( predicate: (T) -> Boolean ): IntThis extension function returns index of the last element matching the given predicate, or -1 if the collection does not contain such element.
✐ Examples
1 Example
In this example,
- We create a list of strings named
list1containing elements"apple", "banana", "cherry". - We use the
indexOfLast()function onlist1with a predicate to find the index of the last element starting with'b'. - Since the last element starting with
'b'is"banana"at index 1 inlist1, the result is 1. - Finally, we print the index to standard output using println statement.
Kotlin Program
fun main(args: Array<String>) {
val list1 = listOf("apple", "banana", "cherry")
val index = list1.indexOfLast { it.startsWith("b") }
println(index)
}Output
1
2 Example
In this example,
- We create a list of integers named
list2containing elements10, 20, 30, 20, 40, 50. - We use the
indexOfLast()function onlist2with a predicate to find the index of the last element equal to20. - Since the last element equal to
20is at index 3 inlist2, the result is 3. - Finally, we print the index to standard output using println statement.
Kotlin Program
fun main(args: Array<String>) {
val list2 = listOf(10, 20, 30, 20, 40, 50)
val index = list2.indexOfLast { it == 20 }
println(index)
}Output
3
3 Example
In this example,
- We create a list of strings named
list3containing elements"red", "blue", "green", "yellow". - We use the
indexOfLast()function onlist3with a predicate to find the index of the last element with a length greater than 10. - Since there is no element in
list3with a length greater than 10, the result is -1. - Finally, we print the index to standard output using println statement.
Kotlin Program
fun main(args: Array<String>) {
val list3 = listOf("red", "blue", "green", "yellow")
val index = list3.indexOfLast { it.length > 10 }
println(index)
}Output
-1
Summary
In this Kotlin tutorial, we learned about indexOfLast() extension function of List: the syntax and few working examples with output and detailed explanation for each example.