Kotlin Set find()
Syntax & Examples
Set.find() extension function
The find() extension function in Kotlin searches for the first element in a set that matches the given predicate and returns it. If no such element is found, it returns null.
Syntax of Set.find()
The syntax of Set.find() extension function is:
fun <T> Set<T>.find(predicate: (T) -> Boolean): T?
This find() extension function of Set returns the first element matching the given predicate, or null if no such element was found.
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.find() returns value of type T?
.
✐ Examples
1 Finding the first even number
Using find() to search for the first even number in a set.
For example,
- Create a set of integers.
- Define a predicate function that returns true for even numbers.
- Use find() to search for the first even number in the set.
- Print the resulting number.
Kotlin Program
fun main() {
val numbers = setOf(1, 3, 5, 6, 7, 8)
val firstEven = numbers.find { it % 2 == 0 }
println(firstEven)
}
Output
6
2 Finding the first string with length greater than 2
Using find() to search for the first string with a length greater than 2 in a set.
For example,
- Create a set of strings.
- Define a predicate function that returns true for strings with a length greater than 2.
- Use find() to search for the first string with a length greater than 2 in the set.
- Print the resulting string.
Kotlin Program
fun main() {
val strings = setOf("a", "ab", "abc", "abcd")
val firstLongString = strings.find { it.length > 2 }
println(firstLongString)
}
Output
"abc"
3 Finding the first non-null value
Using find() to search for the first non-null value in a set.
For example,
- Create a set containing integers and null values.
- Define a predicate function that returns true for non-null values.
- Use find() to search for the first non-null value in the set.
- Print the resulting value.
Kotlin Program
fun main() {
val mixedSet: Set<Int?> = setOf(null, 2, null, 4, 5)
val firstNonNull = mixedSet.find { it != null }
println(firstNonNull)
}
Output
2
Summary
In this Kotlin tutorial, we learned about find() extension function of Set: the syntax and few working examples with output and detailed explanation for each example.