我對 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是優惠券級別的值,值List<Promotion>是促銷串列,由ReminderType優惠券中的每個值過濾
我被困在這里
val result: Map<ReminderType, List<Promotion>> = promotions.map { it.coupons.groupBy { it.reminderType } }
uj5u.com熱心網友回復:
方法之一
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
}
這里我們先把每張優惠券映射到promotion,然后再按優惠券分組
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/329499.html
