The structure of data class
data class ProductDetail(
val name: String,
val price: Int,
val status: Status,
val images: Images
...
)
I have a List<ProductDetail>
and I want to convert it to Map<String, Map<Int, ProductDetail>>
.
I tried looking into associate
and associatedTo
but I am only able to create Map<String, Pair<Int, ProductDetail>>
. Is there a way to do this without the use to a loop in Kotlin?
CodePudding user response:
val mapOfMaps = list.groupBy(ProductDetail::name) // or { it.name }
.mapValues { (name, productDetailsList) ->
productDetailsList.groupBy(ProductDetail::price) // or { it.price }
}
Use groupBy
to easily create a map that groups items into matching lists. Then you can map those lists into inner maps with another groupBy
call.
I am guessing associate
is not the behavior you wanted here, because then every inner map would only contain one item, instead of all items with the matching name
, and all repeated names would be dropped from the data.