[英]How to construct a map from a complicated structure by using groupBy in kotlin
I'm confused about the collection in kotlin.我对 kotlin 中的集合感到困惑。
The structure is a little bit complicated.结构有点复杂。
data class Request(
val region: Region,
val promotions: List<Promotion>,
)
data class Promotion(
var promotionCode: String,
val promotionType: String,
val coupons: List<Coupon>
)
data class Coupon(
val reminderType: ReminderType,
val couponCode: String,
val count: Int,
val couponMultiLanguages: List<CouponDescription>
)
Now I want to get a map, Map<ReminderType, List<Promotion>>
, where key ReminderType
is the val in Coupon level, the values List<Promotion>
is a list of promotions which is filtered by each ReminderType
value in coupon现在我想得到一张地图
Map<ReminderType, List<Promotion>>
,其中键ReminderType
是 Coupon 级别的 val,值List<Promotion>
是List<Promotion>
列表,由优惠券中的每个ReminderType
值过滤
I get stuck here我被困在这里
val result: Map<ReminderType, List<Promotion>> = promotions.map { it.coupons.groupBy { it.reminderType } }
One of the approaches方法之一
val result = promotions.flatMap { p -> //flatMap will flatten the list of list
p.coupons.map {
it to p // this creates a pair of coupon to promotion
}
}.groupBy(
{ it.first.reminderType } // specify reminderType as key selector
) {
it.second // promotion as value, groupBy adds these to list
}
Here we first map each coupon to promotion, and then group by coupon这里我们先把每张优惠券映射到promotion,然后再按优惠券分组
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.