Kotlin Training Program

DOWNLOAD APP

FEEDBACK

Filter

To filter out elements from a list based on some predicate, we have the filter() function.

Following is an example usage of filter() function that filters out planets of mass below the average mass of all planets :

 class Planet(
    val name: String,
    val mass: Double
)

fun main() {
    val planets = listOf(
        Planet("Earth", 5.9724e24),
        Planet("Jupiter", 1.8982e27),
        Planet("Mars", 6.4171e23),
        Planet("Mercury", 3.3011e23),
        Planet("Neptune", 1.0243e26),
        Planet("Pluto", 1.3030e22),
        Planet("Saturn", 5.6834e26),
        Planet("Uranus", 8.6810e25),
        Planet("Venus", 4.8675e24)
    )

    val averageMass = planets.sumOf { it.mass } / planets.size

    planets.filter { it.mass < averageMass }
        .sortedByDescending { it.mass }
        .forEach { println("${it.name} -> ${it.mass}kg") }
}
 

To implement the filter() function,

We can use the List Builder - buildList() function to make the code more concise :

 fun <T> List<T>.filter(
    predicate: (T) -> Boolean
): List<T> {
    return buildList {
        this@filter.forEach {
            if (predicate(it)) add(it)
        }
    }
}
 

Note the use of Labelled this keyword - this@filter. This is needed to avoid ambiguity & refer to the List<T> and not MutableList scope of buildList() function.