Kotlin List find()
Syntax & Examples
Syntax of List.find()
The syntax of List.find() extension function is:
fun <T> Iterable<T>.find(predicate: (T) -> Boolean): T?
This find() extension function of List returns the first element matching the given predicate, or null if no such element was found.
✐ Examples
1 Example
In this example,
- We create a list named
list1
containing integers. - We use the
find
function onlist1
with a predicate that finds the first even number. - The result, which is the first even number in the list, is stored in
result
. - Finally, we print the value of
result
to standard output using theprintln
statement.
Kotlin Program
fun main(args: Array<String>) {
val list1 = listOf(1, 2, 3, 4, 5)
val result = list1.find { it % 2 == 0 }
println(result)
}
Output
2
2 Example
In this example,
- We create a list named
list2
containing strings. - We use the
find
function onlist2
with a predicate that finds the first string with length greater than 5. - The result, which is the first string with length greater than 5 in the list, is stored in
result
. - Finally, we print the value of
result
to standard output using theprintln
statement.
Kotlin Program
fun main(args: Array<String>) {
val list2 = listOf("apple", "banana", "cherry")
val result = list2.find { it.length > 5 }
println(result)
}
Output
banana
3 Example
In this example,
- We create a list named
list3
containing characters. - We use the
find
function onlist3
with a predicate that finds the first lowercase character. - The result, which is the first lowercase character in the list, is stored in
result
. - Finally, we print the value of
result
to standard output using theprintln
statement.
Kotlin Program
fun main(args: Array<String>) {
val list3 = listOf('a', 'b', 'c', 'd', 'e')
val result = list3.find { it.isLowerCase() }
println(result)
}
Output
a
Summary
In this Kotlin tutorial, we learned about find() extension function of List: the syntax and few working examples with output and detailed explanation for each example.