Kotlin List.find()
The List.find() function in Kotlin is used to find the first element in a list that satisfies a given predicate(condition).
Syntax
The syntax of List.find() function is
fun <T> Iterable<T>.find(predicate: (T) -> Boolean): T?
where
Parameter | Description |
---|---|
predicate | A function that takes an element and returns true if the element satisfies the desired condition. |
where T
is the type of elements in the list.
The function takes a predicate as an argument and returns the first element that satisfies the given predicate. If no such element is found, it returns null
.
Example 1: Basic Usage of List.find()
In this example, we shall take a list of integer values in numbers
, and find the first even number in this list, using List.find() with the predicate that the value is even number.
Kotlin Program
fun main() {
val numbers = listOf(1, 3, 5, 8, 7, 10)
val firstEven = numbers.find { it % 2 == 0 }
println(firstEven)
}
Output
8
Example 2: Finding a Specific Object using List.find()
In this example, we take a list of user defined objects of type Person
. Using List.find() function, we have to get the first Person
object whose age
property is greater than 25.
Kotlin Program
data class Person(val name: String, val age: Int)
val people = listOf(
Person("Ram", 22),
Person("Kiran", 30),
Person("Veena", 25)
)
val firstPerson = people.find { it.age > 25 }
println(firstPerson)
Output
Person(name=Kiran, age=30)
Example 3: List.find() where the predicate finds no element
In this example, we shall take a list of integer values in numbers
, and find the first negative number in this list, using List.find(). We shall take the values in the numbers
list, such that there is no negative element.
Kotlin Program
fun main() {
val numbers = listOf(1, 3, 5, 7, 9)
val firstNegative = numbers.find { it < 0 }
println(firstNegative)
}
Output
null
Summary
In this tutorial, we have learnt about List.find() function, its syntax, and usage, with well detailed examples.