Kotlin – Filtering objects in a List based on a property
To filter objects in a list based on a property of the objects, you can use List.filter() function, with the predicate formed using the object property.
Example
In this example, we have to filter a given persons list based on the age property of each object in the list. The following is a step by step process.
- Take a list of objects in persons. A Person object has a name, and age as properties.
- Call filter() function on the persons list, and pass the predicate that the age of the person is greater than 25,
it.age > 25
, whereit
is object in the list. - The filter() function returns a list containing Person objects whose age is greater than 25.
- You may print the returned list to output.
Program
fun main() {
data class Person(val name: String, val age: Int)
val persons = listOf(
Person("Ram", 24),
Person("Maddy", 30),
Person("Krishna", 22),
Person("Vina", 35)
)
val adults = persons.filter { it.age > 25 }
println(adults)
}
Output
[Person(name=Maddy, age=30), Person(name=Vina, age=35)]