1. Overview
In this short article, we’ll introduce Kotlin collection functions find and findLast. These functions work with arrays, lists, and any iterable.
2. Find the first matching element
The format of the find function is
inline fun <T> Array<out T>.find( predicate: (T) -> Boolean ): T?
The predicate can have any valid conditions that return boolean as result. if boolean is true, then the matching is found.
Suppose you have a list of 10 students and you want to find the first student starting with the letter “J” in the list.
val students = listOf("Raj", "Alex", "John", "Jubin", "Mike", "Bob", "Siv", "Praj", "Pramod", "Lisa")
Here, you can use the find function to return the first element matching the given predicate, or null if no such element was found.
val student = students.find { student -> student.startsWith("J") }
student -> student.startsWith(“J”) is a predicate to match the element with starting letter “J”.
Result:
John
Though the names of students John and Jubin start with “J”, the find function will return the first matching result.
Let’s see another valid use case. You have a list of student objects. Each object has a name, department, and id. Suppose you want to find out the student of id 214 and update his department details. In this scenario, you can use the find function.
val johnStudent = StudentModel("John", "Computer", 213) val mikeStudent = StudentModel("Mike", "Computer", 214) val sivStudent = StudentModel("Siv", "Computer", 215) val students = listOf<StudentModel>(johnStudent, mikeStudent, sivStudent) val student = students.find { student -> student.studentId == 214L }
Result:
StudentModel(name=Mike, department=Computer, studentId=214)
3. Find the last matching element
The format of findLast is
inline fun <T> Array<out T>.findLast(
predicate: (T) -> Boolean
): T?
This function returns the last element matching the given predicate, or null if no such element was found. Let’s take the same student list example.
val students = listOf("Raj", "Alex", "John", "Jubin", "Mike", "Bob", "Siv", "Praj", "Pramod", "Lisa") val student = students.findLast { student -> student.startsWith("J") }
The findLast function returns “Jubin” instead of “John” as it is the last matching name with “J”. Below is another example with integers
val numbers = listOf(1, 2, 3, 4, 5, 6, 7) val firstOdd = numbers.find { it % 2 != 0 } val lastEven = numbers.findLast { it % 2 == 0 } println(firstOdd) println(lastEven)If only one matching element is available in the list, then both the find and findLast functions return the same object.
4. Conclusion
In this article, we have seen Kotlin find and findLast functions along with its examples.
You can refer to Kotlin’s official documentation for more information find and findLast.