我对kotlin中的集合感到困惑。
结构有点复杂。
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>
)
现在我想获得一个映射,Map<ReminderType, List<Promotion>>
,其中键ReminderType
是优惠券级别中的val,值List<Promotion>
是促销活动列表,由优惠券
ReminderType
值过滤我被困在这里
val result: Map<ReminderType, List<Promotion>> = promotions.map { it.coupons.groupBy { it.reminderType } }
方法之一
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
}
这里我们首先将每张优惠券映射到促销活动,然后按优惠券
分组