Daniele B
10/15/2020, 9:53 PMdata 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),
) }Quincy
10/15/2020, 10:07 PMdata 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")
}ephemient
10/15/2020, 10:45 PMephemient
10/15/2020, 10:46 PM.groupBy() and .groupingBy() are subtly different. you can get .groupBy() from .groupingBy(), but you can also get much more.ephemient
10/15/2020, 10:48 PMGrouping means you can skip creating the intermediate data structures that .groupBy() forces, if you were going to map over the results anywaynanodeath
10/15/2020, 10:51 PM.groupBy.mapValues is slightly better than .groupBy.map in this case, btw.