Kotlin List.find()
The Kotlin List.find() function is used to get the first element from the List that matches the given predicate.
Syntax
The syntax of List.find() function is
</>
Copy
fun <T> List<T>.find(predicate: (T) -> Boolean): T?
where T
can be any builtin datatype or user-defined datatype.
Examples
In the following example, we have a list of strings. We get the first string whose length is greater than 6.
Kotlin Program
</>
Copy
fun main(args: Array<String>) {
var list = listOf("apple", "banana", "avocado", "cherry")
var result = list.find{ it.length > 6}
println(result)
}
Output
avocado
In the following example, we take a list of numbers, and find the first element which is exactly divisible by 5.
Kotlin Program
</>
Copy
fun main(args: Array<String>) {
var list = listOf(2, 4, 10, 14, 20, 22, 25)
var result = list.find{ it % 5 == 0}
println("Output : " + result)
}
Output
Output : 10
Conclusion
In this Kotlin Tutorial, we learned how to get the first element of this list that matches the given predicate, using Kotlin List.find() function.