Kotlin Set indexOfFirst()
Syntax & Examples
Set.indexOfFirst() extension function
The indexOfFirst() extension function in Kotlin returns the index of the first element matching the given predicate, or -1 if the set does not contain such an element.
Syntax of Set.indexOfFirst()
The syntax of Set.indexOfFirst() extension function is:
fun <T> Set<T>.indexOfFirst(predicate: (T) -> Boolean): Int
This indexOfFirst() extension function of Set returns index of the first element matching the given predicate, or -1 if the collection does not contain such element.
Parameters
Parameter | Optional/Required | Description |
---|---|---|
predicate | required | A function that takes an element and returns true if the element matches the condition. |
Return Type
Set.indexOfFirst() returns value of type Int
.
✐ Examples
1 Finding the index of the first even number
Using indexOfFirst() to find the index of the first even number in a set.
For example,
- Create a set of integers.
- Use indexOfFirst() with a predicate function that checks for even numbers.
- Print the resulting index.
Kotlin Program
fun main() {
val numbers = setOf(1, 3, 5, 6, 7, 8)
val index = numbers.indexOfFirst { it % 2 == 0 }
println(index)
}
Output
3
2 Finding the index of the first string with length greater than 2
Using indexOfFirst() to find the index of the first string with a length greater than 2 in a set.
For example,
- Create a set of strings.
- Use indexOfFirst() with a predicate function that checks for strings with a length greater than 2.
- Print the resulting index.
Kotlin Program
fun main() {
val strings = setOf("a", "ab", "abc", "abcd")
val index = strings.indexOfFirst { it.length > 2 }
println(index)
}
Output
2
3 Finding the index of the first non-null element
Using indexOfFirst() to find the index of the first non-null element in a set.
For example,
- Create a set containing integers and null values.
- Use indexOfFirst() with a predicate function that checks for non-null values.
- Print the resulting index.
Kotlin Program
fun main() {
val mixedSet: Set<Int?> = setOf(null, null, 3, 4, 5)
val index = mixedSet.indexOfFirst { it != null }
println(index)
}
Output
2
Summary
In this Kotlin tutorial, we learned about indexOfFirst() extension function of Set: the syntax and few working examples with output and detailed explanation for each example.