Learn about grouping. Use groupBy to implement the function to build a map that stores the customers living in a given city.
val result =
listOf("a", "b", "ba", "ccc", "ad")
.groupBy { it.length }
result == mapOf(
1 to listOf("a", "b"),
2 to listOf("ba", "ad"),
3 to listOf("ccc"))
// Build a map that stores the customers living in a given city
fun Shop.groupCustomersByCity(): Map<City, List<Customer>> =
TODO()
data class Shop(val name: String, val customers: List<Customer>)
data class Customer(val name: String, val city: City, val orders: List<Order>) {
override fun toString() = "$name from ${city.name}"
}
data class Order(val products: List<Product>, val isDelivered: Boolean)
data class Product(val name: String, val price: Double) {
override fun toString() = "'$name' for $price"
}
data class City(val name: String) {
override fun toString() = name
}
// Build a map that stores the customers living in a given city
fun Shop.groupCustomersByCity(): Map<City, List<Customer>> =
customers.groupBy { it.city }
특정 도시에 거주하는 고객을 저장하는 그룹을 만드는 문제이다.
groupBy
함수groupBy
함수는 컬렉션을 주어진 기준에 따라 그룹으로 묶어주는 함수이다.
이 함수는 Map<Key, Value>
형식의 결과를 반환한다.
Key
는 그룹으로 묶을 기준이고, Value
는 Key
에 맞는 요소들이 리스트로 저장된다.
groupBy
함수에 제공된 람다 표현식의 결과가 된다.: 고객 리스트에서 각 고객의 도시를 기준으로 그룹을 묶어야 한다.
City
를 Key
로 사용하게 되면 해당 도시에 거주하는 고객들의 리스트를 Value
로 설정해주면 된다.