To transform all elements of a list to something new, we have the map()
function.
Following program computes the average mass of all planets using the map()
function. Firstly List<Planet>
is mapped to their masses to get List<Double>
, then average()
function is used :
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.map { it.mass }.average()
println("Average mass = $averageMass kg")
}
To transform List<A>
to List<B>
, map()
function takes a lambda transform: (A) → B
as an argument. This transform operation is then performed on all items in the list and added to a new list.
fun <A, B> List<A>.map(
transform: (A) -> B
): List<B> {
return buildList {
this@map.forEach {
add(transform(it))
}
}
}