https://kotlinlang.org logo
#getting-started
Title
# getting-started
d

Daniele B

10/15/2020, 9:53 PM
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

Quincy

10/15/2020, 10:07 PM
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

ephemient

10/15/2020, 10:45 PM
👏 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

nanodeath

10/15/2020, 10:51 PM
if you do use groupBy,
.groupBy.mapValues
is slightly better than
.groupBy.map
in this case, btw.
👍 1
2 Views