문제

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"))

Task.kt

// Build a map that stores the customers living in a given city
fun Shop.groupCustomersByCity(): Map<City, List<Customer>> =
        TODO()

Shop.kt

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는 그룹으로 묶을 기준이고, ValueKey에 맞는 요소들이 리스트로 저장된다.

  • Key : 그룹의 기준이 되는 값이다. groupBy 함수에 제공된 람다 표현식의 결과가 된다.
  • Value : 해당 키에 속하는 요소들이 리스트로 저장됩니다.

요구사항

: 고객 리스트에서 각 고객의 도시를 기준으로 그룹을 묶어야 한다.

  • CityKey로 사용하게 되면 해당 도시에 거주하는 고객들의 리스트를 Value로 설정해주면 된다.

요구사항 해결

  • customers.groupBy { it.city }
    • 고객 리스트의 각 고객 객체에 대해 도시를 기준으로 그룹을 만든다.
    • 도시가 동일한 고객들이 하나의 그룹으로 묶여서 값(value)이 된다.
    • 이 과정에서 각 도시는 로, 그 도시에 거주하는 고객들의 리스트는 으로 설정된 맵이 생성되어 반환된다.
profile
개발하는 다람쥐

0개의 댓글

관련 채용 정보