https://kotlinlang.org logo
Title
i

Ink

04/24/2022, 5:38 PM
Hi guys, how can I refactor that code?
val productShopInfoItems = productListItemMapper.toShopInfoItems(it.snapshot)

state.productList.value?.forEach { product ->
    productShopInfoItems.forEach {  shop ->
        if(product.productId == shop.productId){
            product.shopInfoItemList += shop
        }
    }
}
product is
data class ProductItem(
    val productId: String = "",
    val productName: String = "",
    var shopInfoItemList: List<ShopInfoResponseItem> = emptyList<ShopInfoResponseItem>()
)
r

Roukanken

04/25/2022, 7:35 AM
shopsByProductId = productShopInfoItems.groupBy { it.productId }
state.productList.value?.forEach { it.shopInfoItemList = shopsByProductId[it.productId] ?: emptyList() }
groupBy is your friend (creates a map of
key -> list of every item where f(item) == key
)
1
👍 1
i

Ink

04/25/2022, 11:58 AM
Thank you