Home > Back-end >  How to construct a map from a complicated structure by using groupBy in kotlin
How to construct a map from a complicated structure by using groupBy in kotlin

Time:10-21

I'm confused about the collection in 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

I get stuck here

val result: Map<ReminderType, List<Promotion>> = promotions.map { it.coupons.groupBy { it.reminderType } }

CodePudding user response:

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

  • Related