【问题标题】:How to construct a map from a complicated structure by using groupBy in kotlin如何在 kotlin 中使用 groupBy 从复杂结构中构建地图
【发布时间】:2021-12-07 19:46:42
【问题描述】:

我对 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&lt;ReminderType, List&lt;Promotion&gt;&gt;,其中键 ReminderType 是优惠券级别中的 val,值 List&lt;Promotion&gt; 是促销列表,由优惠券中的每个 ReminderType 值过滤

我卡在这里

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

【问题讨论】:

  • G2Coupon 类与 Coupon 类不同吗?
  • @sidgate 对不起,它是一样的。已经修好了

标签: java dictionary kotlin group-by collections


【解决方案1】:

一种方法

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
}

这里我们先将每张优惠券映射到促销,然后按优惠券分组

【讨论】:

  • 有什么办法可以按提醒类型分组吗?
猜你喜欢
  • 2017-02-14
  • 2013-11-24
  • 2020-03-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多