Kotlin – Filter objects in List based on a property of object

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.

  1. Take a list of objects in persons. A Person object has a name, and age as properties.
  2. Call filter() function on the persons list, and pass the predicate that the age of the person is greater than 25, it.age > 25, where it is object in the list.
  3. The filter() function returns a list containing Person objects whose age is greater than 25.
  4. 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)]