```data class City ( val name : String = "", ...
# getting-started
d
Copy code
data class City (
    val name : String = "",
    val country : String = "",
    val population : Int = 0,
)

val cities = { listOf(
    City("a", "1", 1305770),
    City("b", "1", 556934),
    City("c", "2", 1924701),
    City("d", "3", 5785861),
    City("e", "3", 4467118),
) }
q
https://pl.kotl.in/3pwJqe5dY
Copy code
data class City (
    val name : String = "",
    val country : String = "",
    val population : Int = 0,
)

fun main() {
    val cities = listOf(
        City("a", "1", 1305770),
        City("b", "1", 556934),
        City("c", "2", 1924701),
        City("d", "3", 5785861),
        City("e", "3", 4467118),
    )
    
    val populationByCountry = cities.groupBy { it.country }
        .map { (country, cities) -> 
            country to cities.sumBy { it.population }
        }.toMap()
    
    println("byPop -> $populationByCountry")
}
👏 2
e
👏 2
.groupBy()
and
.groupingBy()
are subtly different. you can get
.groupBy()
from
.groupingBy()
, but you can also get much more.
using
Grouping
means you can skip creating the intermediate data structures that
.groupBy()
forces, if you were going to map over the results anyway
n
if you do use groupBy,
.groupBy.mapValues
is slightly better than
.groupBy.map
in this case, btw.
👍 1