Kotlin Set lastIndexOf()
Syntax & Examples
Set.lastIndexOf() extension function
The lastIndexOf() extension function in Kotlin returns the last index of the specified element, or -1 if the set does not contain the element.
Syntax of Set.lastIndexOf()
The syntax of Set.lastIndexOf() extension function is:
fun <T> Set<T>.lastIndexOf(element: T): Int
This lastIndexOf() extension function of Set returns last index of element, or -1 if the collection does not contain element.
Parameters
Parameter | Optional/Required | Description |
---|---|---|
element | required | The element to search for in the set. |
Return Type
Set.lastIndexOf() returns value of type Int
.
✐ Examples
1 Finding the last index of an element
Using lastIndexOf() to find the last index of an element in a set.
For example,
- Create a set of integers.
- Use lastIndexOf() to find the last index of a specific element in the set.
- Print the resulting index.
Kotlin Program
fun main() {
val numbers = setOf(1, 2, 3, 4, 5, 3)
val index = numbers.lastIndexOf(3)
println(index)
}
Output
2
2 Finding the last index of a non-existent element
Using lastIndexOf() to find the last index of a non-existent element in a set.
For example,
- Create a set of integers.
- Use lastIndexOf() to find the last index of an element that is not in the set.
- Print the resulting index, which should be -1.
Kotlin Program
fun main() {
val numbers = setOf(1, 2, 3, 4, 5)
val index = numbers.lastIndexOf(6)
println(index)
}
Output
-1
3 Finding the last index of a string in a set
Using lastIndexOf() to find the last index of a string in a set of strings.
For example,
- Create a set of strings.
- Use lastIndexOf() to find the last index of a specific string in the set.
- Print the resulting index.
Kotlin Program
fun main() {
val strings = setOf("a", "b", "c")
val index = strings.lastIndexOf("b")
println(index)
}
Output
1
Summary
In this Kotlin tutorial, we learned about lastIndexOf() extension function of Set: the syntax and few working examples with output and detailed explanation for each example.